Skip to content

Javascript – Promise.any

Last updated on January 30, 2021

Promise.any is a promise combinator that resolves the resulting promise as soon as one of the input promises is fulfilled.

const promises = [
  fetch('/endpoint-a').then(() => 'a'),
  fetch('/endpoint-b').then(() => 'b'),
  fetch('/endpoint-c').then(() => 'c'),
];
try {
  const first = await Promise.any(promises);
  // Any of the promises was fulfilled.
  console.log(first);
  // → e.g. 'b'
} catch (error) {
  // All of the promises were rejected.
  console.assert(error instanceof AggregateError);
  // Log the rejection values:
  console.log(error.errors);
}

If all input promises are rejected, the resulting promise is rejected with an AggregateError object containing an error property that holds an array of rejection values.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments