Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active April 30, 2021 23:56
Show Gist options
  • Save HichamBenjelloun/1f8902db442195d33156576a4e86e1b1 to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/1f8902db442195d33156576a4e86e1b1 to your computer and use it in GitHub Desktop.
Limiting the number of concurrent running promises
let runningPromiseCount = 0;
const examplePromiseRunnerQueue = new Array(10)
.fill(0)
.map((_, idx) => idx)
.map((idx) => {
return async () => {
console.log(
`[${new Date().toISOString()}] Promise ${idx} will run! \n# of running promises: ${runningPromiseCount}`
);
runningPromiseCount++;
return await new Promise((resolve) => {
setTimeout(() => {
resolve(idx);
runningPromiseCount--;
}, idx * 1000);
});
};
});
const run = (promiseRunnerQueue = [], max = promiseRunnerQueue.length) => {
const executeAndDelegateNextCall = async (promiseRunner) => {
try {
await promiseRunner();
} finally {
if (promiseRunnerQueue.length === 0) {
return;
}
const nextPromiseRunner = promiseRunnerQueue.shift();
executeAndDelegateNextCall(nextPromiseRunner);
}
};
promiseRunnerQueue.splice(0, max).forEach(executeAndDelegateNextCall);
};
run(examplePromiseRunnerQueue, 10);
@HichamBenjelloun
Copy link
Author

Example trace output:

[2021-04-29T21:26:31.893Z] Promise 0 will run! 
# of running promises: 0 
[2021-04-29T21:26:31.894Z] Promise 1 will run! 
# of running promises: 1 
[2021-04-29T21:26:31.894Z] Promise 2 will run! 
# of running promises: 2 
[2021-04-29T21:26:31.894Z] Promise 3 will run! 
# of running promises: 3 
[2021-04-29T21:26:31.894Z] Promise 4 will run! 
# of running promises: 4 
[2021-04-29T21:26:31.904Z] Promise 5 will run! 
# of running promises: 4 
[2021-04-29T21:26:32.894Z] Promise 6 will run! 
# of running promises: 4 
[2021-04-29T21:26:34.446Z] Promise 7 will run! 
# of running promises: 4 
[2021-04-29T21:26:35.446Z] Promise 8 will run! 
# of running promises: 4 
[2021-04-29T21:26:36.446Z] Promise 9 will run! 
# of running promises: 4 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment