Hiprup

What is the difference between Promise.race() and Promise.any()?

Both settle based on the first promise, but react to success and failure differently.

  • Promise.race — settles as soon as any promise settles, whether it fulfils or rejects (first to finish wins).

  • Promise.any — waits for the first fulfilment; only rejects if all of them reject.

Use race for timeouts (race against a timer); any for "first successful source wins".

// Promise.race — first to SETTLE (success OR failure)
const timeout = new Promise((_, reject) =>
  setTimeout(() => reject(new Error('Timeout')), 5000)
);
const result = await Promise.race([fetch('/api/data'), timeout]);
// Whichever settles first wins (fetch OR timeout)

// Promise.any — first to SUCCEED (ignores failures)
const fastest = await Promise.any([
  fetch('https://server1.com/data').then(r => r.json()),
  fetch('https://server2.com/data').then(r => r.json()),
  fetch('https://server3.com/data').then(r => r.json())
]);
// Uses whichever server responds successfully first
// Rejected servers are ignored

// Promise.any — all reject = AggregateError
try {
  await Promise.any([
    Promise.reject('err1'),
    Promise.reject('err2')
  ]);
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.errors); // ['err1', 'err2']
}

race: the timeout pattern — if fetch takes longer than 5s, the timeout rejects first. any: try three servers — the first successful response wins, failures ignored. If all three servers fail, AggregateError contains all rejection reasons.

race = first settled (success or failure). any = first succeeded (ignores failures). race for timeouts (practical). any for redundant sources (try multiple, use fastest success). AggregateError when all fail in any.

What is the difference between Promise.race() and Promise.any()? | Hiprup