Created
June 24, 2022 06:54
-
-
Save makenowjust/814668c0f5b003ea9e7fc8938a881066 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default (concurrency = 1) => { | |
let activeConsumerCount = 0; | |
const queue = []; | |
const consume = async () => { | |
if (activeConsumerCount >= concurrency) { | |
return; | |
} | |
activeConsumerCount += 1; | |
while (queue.length > 0) { | |
const task = queue.shift(); | |
try { | |
task.resolve(await task.run()); | |
} catch (err) { | |
task.reject(err); | |
} | |
} | |
activeConsumerCount -= 1; | |
}; | |
return async (run) => { | |
return await new Promise((resolve, reject) => { | |
queue.push({ run, resolve, reject }); | |
consume(); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment