ES2020 - Promise.any

ยท 2 min read
ES2020 - Promise.any

Promise.any() is a method that gets resolved when at least one of the given Promises gets resolved.

It gets as an argument an iterable of Promise objects and returns a single Promise that resolves with value of that very Promise:

const result = await Promise.any([
  new Promise(resolve => setTimeout(() => resolve(66), 1000)),
  Promise.reject(new Error('an error'))

// result = 33;

The result here is equal with 33 since this is the result of the very first Promise that manages to get resolved.

The key difference with Promise.race is that Promise.race returns the value of the very first resolved or rejected Promise while Promise.any cares only about the very first resolved (successful) one.

When all given Promise objects get rejected, then Promise.any rejects and returns the errors. These might be in one of the following format:

  • an array containing all the rejection errors of each Promise passed
  • an AggregateError object, which is an object representing an error when several errors need to be wrapped in a single error

This is something that is not finalized yet so Promise.any is still in stage 3.

This method can become handy when we are happy to move on when at least one Promise resolves and we don't really care about the rest of them. Cheers!!

At the moment of this writing, Promise.any() is in stage 3 of the process which is considered candidate

We can use it with the help of core-js

Did you like this one?

I hope you really did...



Get notified about latest posts and updates once a week!!