May 4, 2023

TypeScript - Promise.any()

The Promise.any() method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one.

This method returns the first fulfilled value and ignores all rejected promises up until the first promise that fulfills. This can be beneficial if we need only one promise to fulfill but we do not care which one does.

Lets see an example:

const p1 = Promise.reject("some error");
const p2 = Promise.resolve("resolve value1");
const p3 = Promise.resolve("resolve value2");

const promises = [p1, p2, p3];

(Promise as any).any(promises)
.then((value) => console.log(value))
.catch((error) => { console.error(error.message);});

Output will be :

resolve value1

In this example, the first promise p1 is rejected, but Promise.any method ignores this and continue to the next promise p2 which get resolved/fulfilled. Once it finds the first fulfilled promise it stops processing further promises.

If all of the input promises are rejected, then it rejects with an AggregateError containing an array of rejection reasons.

See this example:

const p1 = Promise.reject("some error1");
const p2 = Promise.reject("some error2");
const p3 = Promise.reject("some error3");

const promises = [p1, p2, p3];

(Promise as any).any(promises)
.then((value) => console.log(value))
.catch((error) => { console.error(error);});

Output will be :

[AggregateError: All promises were rejected] {
  [errors]: [ 'some error1', 'some error2', 'some error3' ]
}

When all of the input promises are rejected, it generates the AggregateError (array of the rejection error from each input promise).

References:

Related Post(s):

No comments:

Post a Comment