Promise.all (ES2015) vs Promise.allSettled (ES2020). What's changed? πŸ€”

shahzaibkhalid

Shahzaib Khalid

Posted on August 25, 2019

Promise.all (ES2015) vs Promise.allSettled (ES2020). What's changed? πŸ€”

Hey! πŸ‘‹

Check out today's ⚑️ Dev Tip πŸ’‘ πŸ‘‡

Follow me on Twitter @shahzaibkhalid for more Dev Tips! ✨

Let’s say we want to run many promises to execute in
parallel and wait till all of them are ready. 🧐

// some dummy promises to play with 🍭
const p1 = new Promise(resolve => resolve('Shahzaib'));
const p2 = new Promise((_ ,reject) => reject('User does not exists!'));
const p3 = new Promise(resolve => resolve('Lahore'));
Enter fullscreen mode Exit fullscreen mode

Promise.all (short-circuits if any of the promises is rejected)

If any of the passed promises is rejected, the promise
returned by Promise.all immediately rejects with that error. ❌

Promise.all([p1, p2, p3])
  .then(response => console.log(response))
  .catch(error => console.log(error)); // πŸ‘‰'User does not exists!'
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled (does not short-circuits)

Waits for all passed promises to settle (either resolved or rejected). πŸ₯³

The resulting array has:

  • {status: 'fulfilled', value: result} - for successful responses
  • {status: 'rejected', reason: error} - for errors
Promise.allSettled([p1, p2, p3])
  .then(response => console.log(response));

/**
 * πŸ‘‰ [ {status: 'fulfilled', value: 'Shahzaib'},
 *      {status: 'rejected', reason: 'User does not exists!'},
 *      {status: 'fulfilled, value: 'Lahore'} ] πŸš€
 */
Enter fullscreen mode Exit fullscreen mode

Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. πŸ‘€

Peace. ✌️

πŸ’– πŸ’ͺ πŸ™… 🚩
shahzaibkhalid
Shahzaib Khalid

Posted on August 25, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related