Search code examples
javascriptes6-promise

Differences between Promise.all() and Promise.allSettled() in JS?


I was reading the MDN's manual on Promise, and I found these two methods which seem similar to me:

Both of them take an iterable and return an array containing the fulfilled Promises.

So, what is the difference between them?


Solution

  • Promise.all will reject as soon as one of the Promises in the array rejects.

    Promise.allSettled will never reject - it will resolve once all Promises in the array have either rejected or resolved.

    Their resolve values are different as well. Promise.all will resolve to an array of each of the values that the Promises resolve to - eg [Promise.resolve(1), Promise.resolve(2)] will turn into [1, 2]. Promise.allSettled will instead give you [{ status : 'fulfilled', value: 1 }, { status : 'fulfilled', value: 2 }].

    Promise.all([Promise.resolve(1), Promise.resolve(2)])
      .then(console.log);
    Promise.allSettled([Promise.resolve(1), Promise.resolve(2)])
      .then(console.log);

    If one of the Promises rejects, the Promise.all will reject with a value of the rejection, but Promise.allSettled will resolve with an object of { status: 'rejected', reason: <error> } at that place in the array.

    Promise.all([Promise.reject(1), Promise.resolve(2)])
      .catch((err) => {
        console.log('err', err);
      });
    Promise.allSettled([Promise.reject(1), Promise.resolve(2)])
      .then(console.log);