Created
May 1, 2021 13:49
-
-
Save HichamBenjelloun/b845bb909a750cb96d3e49319648b889 to your computer and use it in GitHub Desktop.
Limiting the number of concurrent running promises streamed via a generator
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
const DEFAULT_MAX_CONCURRENT_PROMISES = 5; | |
/** | |
* Runs a stream of promises and ensures only `max` promises are run at a time | |
* @param {*} promiseRunnerGen | |
* @param {*} max | |
*/ | |
const run = (promiseRunnerGen, max = DEFAULT_MAX_CONCURRENT_PROMISES) => { | |
const iterator = promiseRunnerGen(); | |
let runningPromiseCount = 0; | |
const executeAndDelegateNextCall = async (promiseRunner) => { | |
try { | |
runningPromiseCount++; | |
await promiseRunner(); | |
} finally { | |
runningPromiseCount--; | |
const { value: nextPromiseRunner, done } = iterator.next(); | |
if (!done) { | |
executeAndDelegateNextCall(nextPromiseRunner); | |
} | |
} | |
}; | |
let current = iterator.next(); | |
while (!current.done && runningPromiseCount < max) { | |
executeAndDelegateNextCall(current.value); | |
current = iterator.next(); | |
} | |
}; | |
export { run }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment