Promise. all
and Promise.allSettled
is used to iterate over an array of promises. However, both have a few subtle differences, let's understand that in this article.
Promise.all
method
Promise. all
iterates over an array of promises and resolve to the array of values returned by each promise.
js
const tasks = [
new Promise((resolve, reject)=> {
setTimeout(resolve, 1000, "task 1")
}),
new Promise((resolve, reject)=> {
setTimeout(resolve, 2000, "task 2")
}),
new Promise((resolve, reject)=> {
setTimeout(resolve, 3000, "task 3")
}),
]
Promise.all(tasks).then(data => {
console.log(data); // ["task 1", "task 2", "task 3"]
})
If any one of the promises gets rejected then it immediately stops the execution and rejects with the error returned from the rejected promise.
js
const tasks = [
new Promise((resolve, reject)=> {
setTimeout(resolve, 1000, "task 1")
}),
new Promise((resolve, reject)=> {
setTimeout(reject, 2000, "task 2 failed")
}),
new Promise((resolve, reject)=> {
setTimeout(resolve, 3000, "task 3")
}),
]
Promise.all(tasks).then(data => {
console.log(data);
}).catch(error => {
console.log(error); // task 2 failed
})
Promise.allSettled
method
Promise.allSettled
iterates over an array of promises and waits for all the promises to get either resolved or rejected. It resolves to an array of data with each promise's status in the following format.
js
[
{status: "fulfilled", value: value1},
{status: "fulfilled", value: value2},
{status: "rejected", reason: error}
]
Let's see what will be the output of the tasks2
js
const tasks = [
new Promise((resolve, reject)=> {
setTimeout(resolve, 1000, "task 1")
}),
new Promise((resolve, reject)=> {
setTimeout(reject, 2000, "task 2 failed")
}),
new Promise((resolve, reject)=> {
setTimeout(resolve, 3000, "task 3")
}),
]
Promise.allSettled(tasks).then(data => {
console.log(data);
})
// Output
[
{
status: 'fulfilled',
value: 'task 1',
},
{
status: 'rejected',
reason: 'task 2 failed',
},
{
status: 'fulfilled',
value: 'task 3',
},
];