Posted by Arjun on Friday 24th July 2020

Javascript - Promise.any

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.