Promise.race()

Returns a promise that settles the same way as the first promise in the list to settle, whether with success or an error.

Returns
A promise with the result or error of the first promise to settle.
On this page

Example

#
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))

const winner = await Promise.race([wait(300, 'Jack'), wait(100, 'Emma'), wait(200, 'Mia')])

console.log(`First response: ${winner}`)
Console
First response: Emma

Definition and usage

#

The Promise.race() method runs a race between promises. The returned promise takes on the outcome of whichever one settles first, whether that’s a success or an error. The remaining promises keep running, but their results are ignored.

The most common use is a timeout. You race the real operation against a promise that gets rejected after a few seconds. If the operation doesn’t finish in time, you get a timeout error instead of waiting forever.

An empty array gives you a promise that never settles. If you only care about the first success and want errors ignored, use Promise.any().

Syntax

#
Syntax
Promise.race(iterable)

Parameters

#
  • iterable

    array of promises

    The promises taking part in the race.

More examples

#
A timeout for an operation
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))
const timeout = (ms) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), ms))

try {
  const data = await Promise.race([wait(800, 'data from the server'), timeout(300)])
  console.log(data)
} catch (error) {
  console.log(error.message)
}
Console
Timed out

Browser support

#

Widely available

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

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For a timeout on fetch() requests, it’s more convenient to use the signal: AbortSignal.timeout(ms) option, which also aborts the request itself.
  • Remember that the losing promises aren’t canceled. Their operations, such as requests to a server, keep running.

Related entries

#

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