CodeBlanks Logo Icon CodeBlanks

Promise.any

JavaScript course · Advanced · Lesson 73/100

Learn to capture the first fulfilled promise with Promise.any.

Promise.any

Promise.any returns the first promise that fulfils. It ignores rejections and waits until one succeeds. This makes it ideal for picking the fastest answer among several redundant endpoints.

const winner = await Promise.any([
  fetch('/primary'),
  fetch('/backup')
]);

If every promise rejects, it throws an AggregateError; its .errors array holds each rejection reason.

AggregateError

When every promise rejects, Promise.any throws an AggregateError. This special error collects each rejection reason in its .errors array.

try {
  await Promise.any([p1, p2]);
} catch (e) {
  console.log(e.errors);
}

So you can see why each endpoint failed in one place, which makes debugging easier.

Exercise Pick the first success from three endpoints

Define three promises: primary, backup1 and backup2. primary resolves with 'primary' after 100ms (use setTimeout). backup1 resolves with 'backup1' after 50ms. backup2 rejects immediately via Promise.reject. Use Promise.any to capture the first success into winner and log it with console.log.

Show example solution
const primary = new Promise(r => setTimeout(r, 100, 'primary'));
const backup1 = new Promise(r => setTimeout(r, 50, 'backup1'));
const backup2 = Promise.reject('unavailable');
const winner = await Promise.any([primary, backup1, backup2]);
console.log(winner);

Test yourself

  1. Catch the first success

    const fastest = await Promise.____([fetchA(), fetchB(), fetchC()]);
    Show answer
    const fastest = await Promise.any([fetchA(), fetchB(), fetchC()]);
  2. Three promises are passed to Promise.any and all three reject. What happens?

    • An AggregateError is thrown
    • undefined is returned
    • The first rejection reason is returned
    • An empty array is returned
    Show answer

    An AggregateError is thrown — Correct! When all promises reject, Promise.any throws an AggregateError.

  3. Match Promise.any behaviours

    first fulfil
    returns value
    all reject
    AggregateError
    rejections
    ignored
    backup endpoints
    first wins

All lessons in Advanced