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.
Example
#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}`)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
#Promise.race(iterable)Parameters
#iterable
array of promises
The promises taking part in the race.
More examples
#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)
}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 thesignal: 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
#- Promise.any()Returns the result of the first promise to be fulfilled. Rejects only once all of them have failed.
- Promise.all()Waits for every promise to be fulfilled and returns an array of their results. Rejects at the first error.
- setTimeout()Runs a function once, after the given number of milliseconds has passed.
- fetch()Sends an HTTP request and returns a promise with the server’s response (a Response object).
Spotted a mistake or missing an example? Write to us.