Skip to content

Promises - Any Method

Promise.any() takes a list of promises and returns one promise, which is fulfilled with the value of the first promise in the list to be fulfilled. Rejections are ignored unless every promise is rejected, in which case it is rejected with an AggregateError that holds all the reasons.

Use it when several sources can supply the same thing and any working answer will do, such as asking a primary server and two backups for the same file.

This example passes the same three requests to Promise.any() and to Promise.race(). The primary server fails first, after 50 milliseconds:

const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fail = (ms, message) =>
new Promise((resolve, reject) => setTimeout(reject, ms, new Error(message)));
const askServers = () => [
fail(50, 'Primary server is down'),
wait(150, 'backup server A'),
wait(100, 'backup server B'),
];
Promise.any(askServers())
.then((server) => console.log('any() got an answer from', server))
.catch((error) => console.log('any() failed:', error.message));
Promise.race(askServers())
.then((server) => console.log('race() got an answer from', server))
.catch((error) => console.log('race() failed:', error.message));

This prints:

race() failed: Primary server is down
any() got an answer from backup server B

Promise.race() settles with the first result of any kind, which is the failure. Promise.any() passes over it and waits for backup server B, which is the first to succeed.

If no promise is fulfilled, Promise.any() is rejected with an AggregateError. Its errors property is an array of the individual reasons, in the input order:

const fail = (ms, message) =>
new Promise((resolve, reject) => setTimeout(reject, ms, new Error(message)));
Promise.any([fail(50, 'Primary server is down'), fail(100, 'Backup server is down')])
.then((server) => console.log('Got an answer from', server))
.catch((error) => {
console.log(error.name, '-', error.message);
console.log(error.errors.map((e) => e.message));
});

This prints:

AggregateError - All promises were rejected
[ 'Primary server is down', 'Backup server is down' ]

The wording of the message differs between JavaScript engines, so code should check error.errors rather than the message. An empty list is rejected straight away with an empty errors array.

Method Fulfilled when Rejected when
Promise.all() every promise is fulfilled, with an array of values the first promise is rejected
Promise.allSettled() every promise has settled, with an array of result objects never, for a list of promises
Promise.race() the first promise to settle is fulfilled the first promise to settle is rejected
Promise.any() the first promise is fulfilled every promise is rejected

Promise.any() was added in ES2021 and works in all current browsers and Node.

Steve Griffith covers this topic in his video The new Promise any method.