In this section, we will learn what the Promise any() method is and how to use it in JavaScript.
What is Promise any() Method in JavaScript?
Sometimes we want to send a request to multiple external resources like servers and only care about the first one that resolved quicker. In situations like this, we can create a promise for a request to each server and put all of those promises in the `any()` method.
Promise any() Method Syntax:
Promise.any(iterableObject);
Promise any() Method Parameters
The `any()` method takes an iterable object (like an array) that has a bunch of promise-objects as its elements.
Promise any() Method return value
This method creates a promise that will mirror whichever promise inside this iterable object reaches a resolved state first. This means if we have 3 promise objects and two objects reject right away but the last one after 10 seconds gets resolved, the created promise-object is the mirror of the last one that actually resolved.
But if all the promise objects get rejected, then the created promise will be settled to rejection with an AggregateError object as its reason. (The AggregateError will be passed to the rejection handler of the created Promise).
Example: using Promise any() method in JavaScript
const prom1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve("The first promise resolved"); },5000); }); const prom2 = new Promise((resolve, reject)=>{ setTimeout(()=>{ reject("The second promise rejected"); },1000); }) const prom = Promise.any([ prom1, prom2 ]); prom.then(resolve=>{ console.log(resolve); }).catch(reject=>{ console.log(reject); })
Output:
The promise resolved
Here, the Promise-object `prom2` settled to rejection after one second, but there’s another Promise object in the array that we passed to the `any()` method as well. The Promise-object `prom1` after 5 seconds settled to resolve. So the created Promise object via the `any()` method will also settle to resolve and take the reason of the resolved promise as the argument to the resolve-handler.
Example: JavaScript Promise any() Method
Now let’s refactor the example above and this time we make all the promises to settle into rejection.
const prom1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject("The first promise rejected"); },5000); }); const prom2 = new Promise((resolve, reject)=>{ setTimeout(()=>{ reject("The second promise rejected"); },1000); }) const prom = Promise.any([ prom1, prom2 ]); prom.then(resolve=>{ console.log(resolve); }).catch(reject=>{ console.log(reject); })
Output:
AggregateError: All promises were rejected
So because all the Promises were rejected, the created Promise also gets rejected and so the rejection-handler is called for this reason.