Promise.any()

Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an object that is still up for debate: either an array of rejection reasons, or an AggregateError, a new subclass of Error that groups together individual errors. Essentially, this method is the opposite of Promise.all().

Warning! The Promise.any() method is experimental and not fully supported by all browsers. It is currently in the TC39 Candidate stage (Stage 3).

Syntax

Promise.any(iterable);

Parameters

iterable
An iterable object, such as an Array.

Return value

  • An already resolved Promise if the iterable passed is empty.
  • An asynchronously resolved Promise if the iterable passed contains no promises.
  • A pending Promise in all other cases. This returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected.

Description

This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike Promise.all(), which returns an array of resolved values, we only get one resolved value (assuming at least one promise resolves). This can be beneficial if we need only one promise to resolve but we do not care which one does. Also, unlike Promise.race(), which returns the first settled value, this method returns the first resolved value. This method will ignore all rejected promises up until the first promise that resolves.

Fulfillment

If any of the passed-in promises fulfill, the returned promise asynchronously fulfills with the value of the promise that fulfilled, whether or not the other promises have fulfilled or rejected.

  • If an empty iterable is passed, then this method returns (synchronously) an already resolved promise.
  • If any of the passed-in promises fulfill, or are not promises, the promise returned by Promise.any is fulfilled asynchronously.

Rejection

If all of the passed-in promises reject, Promise.any asynchronously rejects with one of two options (which have not yet been agreed upon): either

  • an array containing all the rejection reasons of the iterable passed as the argument, or
  • an AggregateError object, which extends Error, and contains a pointer to an array of exceptions.

Specifications

Specification Status Comment
ESNext Promise.any Proposal Stage 3 Draft Initial definition.

Browser compatibility

No compatibility data found. Please contribute data for "javascript.builtins.Promise.any" (depth: 1) to the MDN compatibility data repository.

See also