Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HichamBenjelloun/b845bb909a750cb96d3e49319648b889 to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/b845bb909a750cb96d3e49319648b889 to your computer and use it in GitHub Desktop.
Limiting the number of concurrent running promises streamed via a generator
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