sindresorhus / p-limit

Run multiple promise-returning & async functions with limited concurrency
MIT License
2.06k stars 106 forks source link

Does p-limit support Promise.allSettled? #45

Closed liweixi100 closed 4 years ago

liweixi100 commented 4 years ago

According to https://www.npmjs.com/package/chunk-promise, p-limit does not support Promise.allSettled. Is that true?

sindresorhus commented 4 years ago

That is false. p-limit supports any promise function (Promise.all, Promise.allSettled, etc) as it's just a wrapped promise itself.

vincerubinetti commented 3 months ago

The mechanism of using this threw me off at a first, so if anyone's stumbling on this and having trouble, here's a simple example of how to use it with allSettled:

import pLimit from "p-limit";

const limiter = pLimit(10);

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const promises = Array(100)
  .fill(null)
  .map(() => async () => {
    console.log("starting");
    await sleep(1000 + Math.random() * 1000);
    if (Math.random() > 0.1) return true;
    else throw Error("error");
  });

console.log(await Promise.allSettled(promises.map(limiter)));

Note the extra () => within the map. This is needed so the promises don't get run right away (while you're mapping through the promises), but instead get run with pLimit tells them they can.