4 Promise Methods you need to know

Subscribe to my newsletter and never miss my upcoming articles

HelloπŸ‘‹ Everyone,

In this article, we are going to see the most used 4 Promise methods.

  • all
  • race
  • any
  • allSettled

1. Promise.all:

Promise.all method accepts an array of promises and returns a new promise that resolves when all the promises are resolved or reject when one of the promises is rejected.

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐢'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.all([dog, cat]).then((values) => {
  // Order of values will be in the same order 
  // in which promises are present in the array
  console.log(values) // ['🐢', '🐈']
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐼'), 2000)
})

Promise.all([bear, panda])
  .then((values) => {
    console.log(values)
  })
  .catch((error) => {
    console.error(error) // 🐻
  })

// Practical Usage:
// This would be useful in the case where 
// you want to fetch data from multiple resources 
// and then consolidate them to form a response 
// before sending it back to the client.
Promise.all([
    fetch('/endpoint0'),
    fetch('/endpoint1'),
      fetch('/endpoint2'),
]).then(response => console.log(response))
.catch(error => console.log(error))

2. Promise.race:

Promise.race method accepts an array of promises and returns a new Promise that resolves or rejects if anyone of the promise is resolved or rejected.

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐢'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.race([dog, cat]).then((value) => {
// value will be the resolved value of 
// first promise which resolved.
  console.log(value) // '🐢'
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐼'), 2000)
})

Promise.race([bear, panda])
  .then((value) => {
    console.log(value)
  })
  .catch((error) => {
  // value will be the rejected value of 
  // first promise which was rejected.
    console.error(error) // 🐻
  })

// Practical Usage:
// Here Promise will throw 'request timeout' 
// if the api call takes more than 30 seconds
Promise.race([
    fetch('/endpoint'),
    new Promise(function (resolve, reject) {
      setTimeout(() => 
        reject(new Error('request timeout')), 30000)
    })
]).then(response => console.log(response))
.catch(error => console.log(error))

3. Promise.any:

Promise.any method accepts an array of promises and returns a new Promise that resolves if anyone of the promise is resolved or rejected if all the promises are rejected.

Note: At the time of writing this is still in the experimental phase, not supported by all browsers and platforms yet

Polyfill : Promise.any

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐢'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.any([dog, cat]).then((value) => {
  // value will be the resolved value of 
 // first promise which resolved.
  console.log(value) // '🐈'
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐼'), 2000)
})

Promise.any([bear, panda])
  .then((value) => {
    console.log(value)
  })
  .catch((error) => {
  // Array of rejected values
    console.error(error) // ['🐻','🐼']
  })

// Practical Usage:
// This can be used if we have multiple async calls 
// and we are only interested in the first successful one.
Promise.any([
    fetch('/endpoint'),
    fetch('/alternateEndpoint'),
    })
]).then(response => console.log(response))
.catch(error => console.log(error))

4. Promise.allSettled:

Promise.allSettled method accepts an array of promises and returns a new Promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects with fields status, value || reason.

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐢'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐈'), 2000)
})

Promise.allSettled([dog, cat]).then((values) => {
  console.log(values); 
// [{ status: 'fulfilled', value: '🐢' },
// { status: 'rejected', // reason: '🐈' }]
});


// Practical Usage:
// I have mostly used this for batch processing where 
// we identify the failed ones and retry separately.
Promise.allSettled([
    fetch('/endpoint0'),
    fetch('/endpoint1'),
    })
]).then(response => console.log(response))

Bonus Tip:

Did you know that Promise constructor callback doesn't short circuit if the promise is resolved or rejected?

const dog = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('🐢');
    console.log('I am still executing!!');
  }, 1000);
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('🐈');
    console.log('Even I am!!');
  }, 2000)
})

Promise.all([dog, cat]).then((values) => {
  console.log(values)
}).catch((error) => {
  console.log('error =>',error);
})

/*
Console Output:
I am still executing!!
Even I am!!
error => 🐈
*/

Please like and share if you find this interesting!πŸ™‚

No Comments Yet