Promise.any() – What Is the JavaScript Promise any() Method?
Promise.any() is a static method of the Promise
constructor function. It returns a new promise object after JavaScript fulfills any item in the iterable value you’ve provided as its argument.
Syntax of the Promise.any()
Static Method
Section titled “Syntax of the Promise.any() Static Method”Promise.any(iterable);
- The
any()
method’s iterable argument’s items can be promises, thenables, or any of JavaScript’s data types. Promise.any()
will automatically pass each of its iterable argument’s items throughPromise.resolve()
. Therefore,any()
will eventually resolve all its iterable argument’s values to a fully-fledged promise object.
Example of Promise.any()
Returning a Fulfilled Promise
Section titled “Example of Promise.any() Returning a Fulfilled Promise”Promise.any(["Orange", Promise.resolve(24), 715]);
// The invocation above will return:Promise { <state>: "fulfilled", <value>: "Orange"}
The snippet above returned a fulfilled promise immediately after JavaScript fulfilled an item in the array argument.
When Does Promise.any()
Return a Fulfilled Promise?
Section titled “When Does Promise.any() Return a Fulfilled Promise?”Promise.any()
returns a fulfilled promise when JavaScript resolves any item in the iterable argument to a fulfilled state.
Here’s an example:
const item1 = Promise.reject(24);const item2 = Promise.reject(715);const item3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("Orange"); }, 30000);});const item4 = "Pinkmelon";
Promise.any([item1, item2, item3, item4]).then((value) => { console.log(value);});
// The invocation above will return: "Pinkmelon"
The snippet above returned "Pinkmelon"
because it is the value of the first fulfilled promise.
What Happens If Promise.any()
Doesn’t Resolve to a Fulfilled Item?
Section titled “What Happens If Promise.any() Doesn’t Resolve to a Fulfilled Item?”Suppose none of the items in the iterable object resolved to a fulfilled state. In that case, the any()
method will return a rejected promise based on the reason of an AggregateError
.
Here’s an example:
Promise.any([Promise.reject("Pinkmelon"), Promise.reject(24)]);
// The invocation above will return:Promise { <state>: "rejected", <reason>: AggregateError }
The snippet above returned a rejected promise object with an AggregateError
reason because all the array argument’s items resolved to a rejected state.