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!๐
Top comments (4)
Hi @kannandev. This is an interesting topic, but those images are hard to read on mobile.
Could you rewrite it using Markdown code blocks?
docs.github.com/en/free-pro-team@l...
Hi, @Camilio Thanks for your feedback will update it asap.
Awesome, thanks!
Done @Camilio, Thanks for the link I didn't know that dev.to markdown supported syntax highlighting