Promise.all is an array method that takes an array of promises and returns a promise that resolves with an array of results from each promise in the original array. It allows us to perform multiple async tasks simultaneously and wait for all of them to resolve before proceeding.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Task 1'), 2000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Task 2'), 3000);
});
Promise.all([promise1, promise2]).then(values => console.log(values)); // ['Task 1', 'Task 2']
Promise.allSettled, on the other hand, returns a promise that resolves with an array containing objects representing the status (fulfilled or rejected) and value (if present) of each promise in the original array.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Task 1'), 2000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => reject('Task 2 failed'), 3000);
});
Promise.allSettled([promise1, promise2]).then(results =>
console.log(results)); // [{status: 'fulfilled', value: 'Task 1'}, {status: 'rejected', reason: 'Task 2 failed'}]
So, in summary, Promise.all is used when we want to wait for all promises to resolve before proceeding, while Promise.allSettled returns a promise that resolves with objects representing the status and value of each promise. We can use both methods depending on our specific needs.