Promise.all
is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all
will reject immediately.
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('one'), 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 2000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('three'), 3000);
});
const p4 = new Promise((resolve, reject) => {
setTimeout(() => resolve('four'), 4000);
});
const p5 = new Promise((resolve, reject) => {
reject(new Error('reject'));
});
Promise.all([p1, p2, p3, p4, p5])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.error(error.message)
});
It is possible to change this behavior by handling possible rejections:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('p1_delayed_resolution'), 1000);
});
const p2 = new Promise((resolve, reject) => {
reject(new Error('p2_immediate_rejection'));
});
Promise.all([
p1.catch((error) => error),
p2.catch((error) => error),
]).then((values) => {
console.log(values[0]);
console.error(values[1]);
})