Handling Promise.any Failures
You'll learn how to catch and debug the AggregateError that Promise.any throws when all promises reject.
When you use Promise.any(), it succeeds as soon as any promise fulfills. But what happens when all promises reject? Unlike Promise.race() which just returns the first settled promise (whether fulfilled or rejected), Promise.any() waits for all rejections and then throws a special error called AggregateError.
What Is AggregateError?
AggregateError is a special error object that bundles multiple errors together. It has an errors property containing an array of all the rejection reasons from the failed promises.
Think of it like a complaint box: if every single option fails, you get back the box containing all the individual complaints, not just the first one.
Catching and Inspecting the Failures
const p1 = Promise.reject(new Error('Server A down'));
const p2 = Promise.reject(new Error('Server B down'));
const p3 = Promise.reject(new Error('Server C down'));
Promise.any([p1, p2, p3])
.then(result => console.log('Success:', result))
.catch(error => {
console.log('All promises failed!');
console.log('Error type:', error.name); // "AggregateError"
console.log('Number of failures:', error.errors.length);
// Inspect each individual failure
error.errors.forEach((err, index) => {
console.log(`Promise ${index + 1} failed:`, err.message);
});
});
// Output:
// All promises failed!
// Error type: AggregateError
// Number of failures: 3
// Promise 1 failed: Server A down
// Promise 2 failed: Server B down
// Promise 3 failed: Server C down
The errors array preserves the order of your original promises, making it easy to trace which specific fallback option failed and why.
Key Takeaway: When Promise.any() fails, catch the AggregateError and inspect its errors property to access all individual rejection reasons for debugging.