ECMAScript 2021
is the latest JavaScript version
that introduced multiple new features
to the JavaScript language.
In this blog, we will cover
Promise.any() method and AggregateError
that was a part of
ECMAScript 2021
addition.
Promise.any() method accepts a list
of Promise objects as an iterable object
and, as soon as one of the promises from the
list fulfills, it returns a single promise
that resolves with the value from that promise.
If no promise in the iterable is fulfilled, then
the returned promise is rejected with an
AggregateError, which is a new subclass of the Error.
Let’s take an example to understand it better.
In the above example, we are passing
three different promises to Promise.any method
for fetching a todo item using a
fake API.
promise1 is the first promise to be fulfilled
so its value (a todo object) is returned from
the Promise.any method and printed to the
console.
Syntax
Promise.any(iterable);
Return value
An already rejected Promise if the iterable
passed is empty.
An asynchronously resolved Promise if the iterable
passed contains no promises.
First resolved value, if any of the
promises in the given iterable resolves.
Error if all the promises are rejected.
Promise.race vs Promise.any
Promise.race() returns the first
settled value (either fulfillment or rejection)
from a list of promises while the
Promise.any() returns the first fulfilled
value.
Let’s take an example to understand it better.
In the above example
promise1 will fetch a todo item
from an endpoint but, promise2 will
be instantly rejected.
As we know, Promise.race returns the
first promise that is either resolved or
rejected from a list of promises, so the
value of promise2 is returned
as it is instantly rejected.
But, in the case of Promise.any, the first resolved
value is returned, so we get a todo object as
an output.
AggregateError
AggregateError is an object that is
thrown when multiple errors need to
be reported by an operation.
It takes multiple iterable errors
instances and wraps them in a single error.