Categories
JavaScript Answers

How to limit concurrency when using JavaScript’s Promise.all()?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *