Sometimes, we want to limit concurrency when using ES6’s Promise.all()
.
In this article, we’ll look at how to limit concurrency when using ES6’s Promise.all()
.
How to limit concurrency when using ES6’s Promise.all()?
To limit concurrency when using ES6’s Promise.all()
, we can use the p-limit
package.
To install it, we run
npm i p-limit
For instance, we write
const pLimit = require('p-limit');
const limit = pLimit(3);
const urls = [
"http://www.exampleone.com/",
"http://www.exampletwo.com/",
"http://www.examplethree.com/",
"http://www.examplefour.com/",
]
const promises = urls.map(url => {
return limit(() => fetchData(url));
});
(async () => {
const result = await Promise.all(promises);
console.log(result);
})();
to call pLimit
with 3 to return the limit
function that limits the number of concurrent promises to 3.
Then we call urls.map
with a callback that returns the promise that’s returned by limit
.
And then call Promise.all
with promises
to return the result
s from the promises.
Conclusion
To limit concurrency when using ES6’s Promise.all()
, we can use the p-limit
package.