Sijin T V
Sijin T V A passionate Software Engineer who contributes to the wonders happenning on the internet

Promise.any() – when you need the first to fulfill

In modern JavaScript we have several Promise combinators (Promise.all, Promise.race, Promise.allSettled). With the release of ES2021 you also got Promise.any — a lesser-used but powerful tool when you care about the first fulfilled Promise, not the first settled one.

What is Promise.any()

Promise.any(iterable) takes an iterable of Promises and returns a single Promise that fulfills as soon as any of the input promises fulfills. If all of the input promises reject, it returns a promise that rejects with an AggregateError.

Why use it instead of Promise.race()

  • Promise.race() settles as soon as any promise settles (resolve or reject).
  • Promise.any() resolves as soon as any promise resolves (i.e., fulfils). If one resolves quickly, you don’t wait for the rest.
  • Example: pinging multiple servers, you want the first successful response — Promise.any() is ideal.

Example

1
2
3
4
5
6
7
8
9
10
11
const p1 = fetch('/server1').then(resp => resp.json());
const p2 = fetch('/server2').then(resp => resp.json());
const p3 = fetch('/server3').then(resp => resp.json());

Promise.any([p1, p2, p3])
  .then(result => {
    console.log('First successful result:', result);
  })
  .catch(error => {
    console.error('All failed:', error);
  });

Caveats

  • If all promises reject, you get an AggregateError with .errors property.

  • Not supported in older browsers without polyfill.

  • Doesn’t cancel the other promises — they still run (you could build cancellation logic yourself).

  • Monitoring or debugging can be trickier if many promises live on.

When to use

  • Multiple APIs/mirrors and you want the first success.

  • Redundant service endpoints.

  • Race-to-fulfill scenarios rather than race to settle (which may reject).

Summary

Promise.any() is a succinct way to get the first successful result out of many asynchronous operations, improving performance in the right scenarios. It’s part of your JavaScript toolbox for modern asynchronous workflows.

comments powered by Disqus