What is Promise.any in JavaScript?

Promise.any will return the first promise that is resolved in an iterable list of promises.

You can find the proposal for this feature here.

let promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'Resolves after 100ms'));
let promise2 = new Promise((resolve) => setTimeout(resolve, 500, 'Resolves after 500ms'));
let promises = [promise1, promise2];
// try in browser console
Promise.any(promises)
.then( value => console.log(value));
// output
// Resolves after 100ms

In the above example, the first promise to be resolved is promise2. As soon as any one of the promises is resolved, the resolved value will be returned. In our case, promise2 is resolved and “Resolves after 100ms” is returned.

If any of the promises is rejected, it is skipped and Promise.any checks for the resolved promise.

let promise1 = new Promise((resolve, reject) => setTimeout(reject, 0) ); // first promise is rejected, it will not be considered
let promise2 = new Promise((resolve) => setTimeout(resolve, 500, 'Resolves after 500ms'));
let promises = [promise1, promise2];
// try in browser console
Promise.any(promises)
.then( value => console.log(value));
// output
// Resolves after 500ms

In the code above, promise1 is rejected, and therefore skipped, and Promise.any checks for a resolved promise.

If all the promises are rejected, or if the promise list is empty, then we will get the AggregateError.

// all promise are rejected
let promise1 = new Promise((resolve, reject) => setTimeout(reject, 0) );
let promise2 = new Promise((resolve, reject) => setTimeout(reject, 0) );
let promises = [promise1, promise2];
// try in browser console
Promise.any(promises)
.then( value => console.log(value))
.catch(error => console.log(error)); //AggregateError: All promises were rejected
// empty promise list
promises = [];
Promise.any(promises)
.then( value => console.log(value))
.catch(error => console.log(error));//AggregateError: All promises were rejected

The Promise.any method returns:

  • a rejected promise if all promises are rejected or if the promise list is empty
Promise.any([])
.then( value => console.log(value));
// output
// Promise {<rejected>: AggregateError: All promises were rejected}
  • an asynchronously-resolved promise if the iterable passed contains no promises (contains values other than a Promise)
Promise.any([1,2,3])
.then( value => console.log(value));
// in console
// 1
// Promise {<fulfilled>: undefined}
  • a pending promise, in all other cases, which will be resolved if any one of the promises from the promise list are resolved
let promise = new Promise((resolve) => setTimeout(resolve, 500, 'Resolves after 100ms'));
Promise.any([promise])
.then( value => console.log(value));
// output
// Promise {<pending>}

We can use Promise.any in a situation where…

Let’s say, we have three images of cool drinks. We can request all three at the same time and display the first image received.

Free Resources