Course contentsShow
← JavaScript
Lesson 1315 of 2,72329. PromisesFree lesson

AggregateError in Promise.any

Handle the special error thrown when all promises in Promise.any reject.

AggregateError in Promise.any

What you'll learn: How Promise.any signals failure when all promises reject by throwing a special AggregateError that wraps every rejection reason.

The Unique Failure Case

Unlike Promise.all (which rejects on the first failure) or Promise.allSettled (which never rejects), Promise.any only rejects when every single promise in the array fails. When this happens, JavaScript doesn't just give you one error—it gives you an AggregateError containing all the individual rejection reasons.

Think of it like a talent show where judges need just one "yes" vote to advance a contestant. If every judge says "no," you get a summary report of all their feedback, not just the first rejection.

How AggregateError Works

const p1 = Promise.reject(new Error('Server timeout'));
const p2 = Promise.reject(new Error('Network error'));
const p3 = Promise.reject(new Error('Invalid response'));

Promise.any([p1, p2, p3])
  .catch(err => {
    console.log(err.name);           // "AggregateError"
    console.log(err.message);        // "All promises were rejected"
    console.log(err.errors);         // Array of all three errors
    console.log(err.errors[0].message); // "Server timeout"
    console.log(err.errors.length);  // 3
  });

The .errors property is the key—it's an array containing every rejection reason in the original order.

Practical Handling

Promise.any([fetchFromServer1(), fetchFromServer2()])
  .then(data => console.log('Success:', data))
  .catch(aggregateError => {
    console.log('All servers failed:');
    aggregateError.errors.forEach((err, i) => {
      console.log(`Server ${i + 1}: ${err.message}`);
    });
  });

Key Takeaway: When all promises in Promise.any reject, it throws an AggregateError with an .errors array containing every individual rejection reason, allowing you to inspect why every option failed.