Created
August 13, 2023 20:34
-
-
Save adrian154/4532d4120f8f269cff56a73104b4c2a8 to your computer and use it in GitHub Desktop.
This file contains 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
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