Promise.any()

Returns the result of the first promise to be fulfilled. Rejects only once all of them have failed.

Returns
A promise fulfilled with the value of the first successful promise, or rejected with an AggregateError.
On this page

Example

#
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))
const fail = (ms, message) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))

const source = await Promise.any([
  fail(100, 'Server A is down'),
  wait(300, 'Server B'),
  wait(200, 'Server C')
])

console.log(`Data from: ${source}`)
Console
Data from: Server C

Definition and usage

#

The Promise.any() method waits for the first success. Errors from individual promises are ignored as long as at least one still has a chance to be fulfilled. That’s what sets it apart from Promise.race(), where the first error can also win.

If every promise is rejected, Promise.any() rejects with an AggregateError. It has an errors field with an array of every rejection reason, listed in the order the promises were passed.

A typical use case is fetching the same resource from several sources, such as backup servers, and using whichever one responds correctly first.

Syntax

#
Syntax
Promise.any(iterable)

Parameters

#
  • iterable

    array of promises

    The promises among which the first success counts.

More examples

#
All promises rejected
JavaScript
try {
  await Promise.any([
    Promise.reject(new Error('No network')),
    Promise.reject(new Error('Server under maintenance'))
  ])
} catch (error) {
  console.log(error.name)
  console.log(error.errors.map((e) => e.message))
}
Console
AggregateError
['No network', 'Server under maintenance']
Comparison with Promise.race()
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))
const fail = (ms, message) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))

const tasks = () => [fail(100, 'Fast error'), wait(200, 'Slower success')]

console.log(await Promise.any(tasks()))

try {
  await Promise.race(tasks())
} catch (error) {
  console.log(error.message)
}
Console
Slower success
Fast error

Browser support

#

Widely available · since 2020

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • When handling an error from Promise.any(), look at error.errors. You’ll find the causes of every failure there.
  • When the first outcome matters regardless of whether it’s a success or an error, use Promise.race().

Related entries

#

Spotted a mistake or missing an example? Write to us.