Sometimes, we want to limit concurrency when using JavaScript’s Promise.all().
In this article, we’ll look at how to limit concurrency when using JavaScript’s Promise.all().
How to limit concurrency when using JavaScript’s Promise.all()?
To limit concurrency when using JavaScript’s Promise.all(), we can call splice
on the promise array to return a new promise functions array with fewer items than the original.
For instance, we write
while (funcs.length) {
await Promise.all(funcs.splice(0, 100).map((f) => f()));
}
to call funcs.splice
to remove the firs 100 items from the funcs
promise functions array and return them in a new array.
Then we call map
to call f
to return the promises.
And we use Promise.all
to run the promises in parallel.
We use the while loop to run all the promises in funcs
until they’re all removed from it.
Conclusion
To limit concurrency when using JavaScript’s Promise.all(), we can call splice
on the promise array to return a new promise functions array with fewer items than the original.