Promises - AllSettled Method
Video
JavaScript Notes
JavaScript
// Promise.allSettled() vs Promise.all() and Promise.race()
let p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 1);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 2);
});
let p3 = new Promise((resolve, reject) => {
reject(3);
});
let p4 = new Promise((resolve, reject) => {
setTimeout(reject, 100, 4);
});
Promise.race([p1, p2, p3, p4])
.then((resp) => {
console.log('FIRST of four responses', { resp });
})
.catch((err) => {
console.error(`CATCH ERROR ${err}`);
});
Promise.all([p1, p2, p3, p4])
.then(([r1, r2, r3, r4]) => {
console.log('ALL FOUR responses... if all were good');
})
.catch((err) => {
console.error(`CATCH ERROR ${err}`);
});
Promise.allSettled([p1, p2, p3, p4]) // waits until all Promises are finished, regardless of whether they resolved or rejected
.then((responses) => {
console.log('finished with ALL FOUR');
responses.forEach((resp, index) => {
console.log(index, { resp });
});
})
.catch((err) => {
console.error(`CATCH ERROR ${err}`);
});
Feedback
Submit and view feedback