The Promise.any() method is a new addition to the Promise API in JavaScript, introduced in ECMAScript 2021.
It allows developers to create a Promise that is fulfilled as soon as any one of the input Promises is fulfilled, or rejected if all the input Promises are rejected.
The method takes an array of Promises as input, and returns a new Promise that resolves with the value of the first Promise in the array that fulfills.
If all the Promises in the array reject, then the new Promise is rejected with an AggregateError. This error contains an array of all the rejection reasons from the input Promises.
The Promise.any() method is similar to Promise.race(), but with some key differences. Promise.race() returns a Promise that resolves or rejects as soon as any one of the input Promises resolves or rejects. In contrast, Promise.any() only resolves when at least one Promise fulfills, and rejects only when all Promises in the input array are rejected.
Here’s an example of how Promise.any() can be used:
const promise1 = Promise.resolve(1);
const promise2 = Promise.reject("Error 2");
const promise3 = Promise.reject("Error 3");
Promise.any([promise1, promise2, promise3])
.then((value) => console.log(value))
.catch((error) => console.log(error));
In this example, the first Promise (promise1) resolves immediately with the value of 1. The second and third Promises (promise2 and promise3) both reject with different error messages. Since at least one Promise fulfills (promise1), the new Promise returned by Promise.any() is also fulfilled with the value of 1. The catch block is not executed in this case.
Now let’s modify the example so that all Promises in the input array reject:
const promise1 = Promise.reject("Error 1");
const promise2 = Promise.reject("Error 2");
const promise3 = Promise.reject("Error 3");
Promise.any([promise1, promise2, promise3])
.then((value) => console.log(value))
.catch((error) => console.log(error));
In this case, all Promises in the input array reject. As a result, the new Promise returned by Promise.any() is also rejected with an AggregateError that contains an array of all the rejection reasons from the input Promises. The catch block is executed, and the error message “AggregateError: All Promises rejected” is logged to the console.
The Promise.any() method can be useful in situations where you want to perform multiple asynchronous operations in parallel, but only need the result of the first one to complete successfully. It can also be used to implement retry logic, where you retry an operation with different parameters until it succeeds.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.