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
- 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
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?
Promise.any()
returns a fulfilled promise when JavaScript resolves any item in the iterable argument to a fulfilled state.
Here’s an example:
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?
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:
The snippet above returned a rejected promise object with an AggregateError
reason because all the array argument’s items resolved to a rejected state.