Thursday, June 9, 2022

What is difference between promise.all() and promise.settleAll

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);

References

https://stackoverflow.com/questions/59784175/differences-between-promise-all-and-promise-allsettled-in-js

No comments:

Post a Comment