Course contentsShow
← JavaScript
Lesson 1975 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

AggregateError in Promise.any

When all promises reject, Promise.any throws an AggregateError containing all rejection reasons.

AggregateError in Promise.any

You'll learn: What happens when all promises passed to Promise.any reject, and how to access all the rejection reasons through AggregateError.

The Unhappy Path of Promise.any

Remember that Promise.any fulfills as soon as any promise succeeds. But what if they all fail? Unlike Promise.race (which just gives you the first settled promise's result), Promise.any needs a special way to tell you "every single option failed."

That's where AggregateError comes in.

What Is AggregateError?

When all promises reject, Promise.any throws an AggregateError — a special error object that bundles all the individual rejection reasons into one neat package. It's like a bag containing every failure message.

const p1 = Promise.reject('Server offline');
const p2 = Promise.reject('Network timeout');
const p3 = Promise.reject('DNS failed');

Promise.any([p1, p2, p3])
  .catch(error => {
    console.log(error.name); // "AggregateError"
    console.log(error.message); // "All promises were rejected"
    console.log(error.errors); // Array: ['Server offline', 'Network timeout', 'DNS failed']
  });

Accessing Individual Failures

The errors property contains an array of all rejection reasons in the same order as the original promises:

Promise.any([p1, p2, p3])
  .catch(err => {
    err.errors.forEach((reason, index) => {
      console.log(`Promise ${index + 1} failed: ${reason}`);
    });
  });

Think of it this way: If Promise.any is trying multiple backup plans simultaneously, AggregateError is the debriefing that explains why every single backup failed.

Key Takeaway: When all promises reject, Promise.any throws an AggregateError whose .errors property contains an array of all individual rejection reasons.