4 Promise Methods you need to know
Kannan
Posted on October 1, 2020
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!π
Posted on October 1, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.