Skip to content

Instantly share code, notes, and snippets.

@makenowjust
Created June 24, 2022 06:54
Show Gist options
  • Save makenowjust/814668c0f5b003ea9e7fc8938a881066 to your computer and use it in GitHub Desktop.
Save makenowjust/814668c0f5b003ea9e7fc8938a881066 to your computer and use it in GitHub Desktop.
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