Understanding Promise.any
You'll learn: How Promise.any lets you race multiple promises and get the first successful result, ignoring failures unless everything fails.
The Core Idea
Promise.any accepts an array of promises and returns a new promise that fulfills as soon as any one of those promises fulfills. It essentially races them, but only cares about winners. Rejections are ignored unless all promises reject, in which case you get an AggregateError containing all the rejection reasons.
Think of it like sending multiple delivery drivers to pick up your package from different locations. You don't care which driver succeeds first—you just want your package. Only if all drivers fail do you get an error report.
How It Works
const promise1 = Promise.reject('Failed server 1');
const promise2 = Promise.resolve('Success from server 2');
const promise3 = Promise.reject('Failed server 3');
Promise.any([promise1, promise2, promise3])
.then(result => console.log(result)) // "Success from server 2"
.catch(error => console.log(error));
Even though two promises rejected, Promise.any returns the one successful result.
All Failures Scenario
const fail1 = Promise.reject('Error A');
const fail2 = Promise.reject('Error B');
const fail3 = Promise.reject('Error C');
Promise.any([fail1, fail2, fail3])
.catch(error => {
console.log(error.name); // "AggregateError"
console.log(error.errors); // ["Error A", "Error B", "Error C"]
});
When everything fails, you get an AggregateError that collects all rejection reasons in its errors property.
When to Use It
Perfect for scenarios where you have multiple fallback sources (like trying different API endpoints) and you only need one to succeed.
Key Takeaway: Promise.any returns the first fulfilled promise and ignores rejections unless all promises reject, making it ideal for fallback strategies where any successful result will do.