Skip to content

Instantly share code, notes, and snippets.

@adrian154
Created August 13, 2023 20:34
Show Gist options
  • Save adrian154/4532d4120f8f269cff56a73104b4c2a8 to your computer and use it in GitHub Desktop.
Save adrian154/4532d4120f8f269cff56a73104b4c2a8 to your computer and use it in GitHub Desktop.
module.exports = (func, concurrency) => {
let numRunning = 0;
const queue = [];
const invoke = ({args, resolve, reject}) => {
func(...args)
.then(resolve)
.catch(reject)
.finally(() => {
if(queue.length > 0) {
invoke(queue.shift());
} else {
numRunning--;
}
});
};
return (...args) => new Promise((resolve, reject) => {
if(numRunning < concurrency) {
numRunning++;
invoke({args, resolve, reject});
} else {
queue.push({args, resolve, reject});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment