Promise.any() in ES2021 Javascript

Mahmut Sürekçi
2 min readJan 18, 2021

I find it exciting when new Promise functions are introduced as it is an integral part of a lot of codebases.

In ES2021 a new function is introduced; Promise.any()

Promise.any() takes a collection of promises and returns the first promise that is fulfilled.

If you are familiar with the Promise.race function this might sound similar. The important distinction is the fulfilment of the promise. Promise.race will return the first promise resolved or rejected whereas Promise.any will return the first promise to be fulfilled or in other words, resolved.

Below is an example code snippet to demonstrate the difference between the two functions:

(async () => {
const reject = Promise.reject("bad");
const resolve = Promise.resolve("good");
try {
const resultAny = await Promise.any([reject, resolve]);

console.log(resultAny);
// Expected output: "good"
} catch (error) {
console.error(error);
// This catch block will not be entered because one of the promises has resolved/fulfilled
}
try {
const resultRace = await Promise.race([reject, resolve]);

console.log(resultRace);
// This will not be logged because the reject promise will win the race and will be caught in the catch
} catch (error) {
// This will be logged out
console.error("We have caught the error");
}
})();

Promise.any() will probably be most useful when you don’t mind if one of the resources you are calling fails as long as one of them is fulfilled. In real life this may be APIs that potentially provide the same resource but, you don’t know which one is going to be the quickest and to improve performance you take this approach.

If all promises passed into Promise.any() fails the function will throw an AggregateError with an errors property which will contain all the errors thrown by the promises to help you debug any issues.

It’s exciting to see functions like this introduced. It would have been possible to do the same thing with existing features but, this function makes it easier for us developers.

Some useful links for more reading:

--

--