.race()

karel.de.smetoutlook.com's avatar
Published Jul 27, 2021Updated Aug 17, 2023
Contribute to Docs

Returns the first Promise in an iterableObject that is either resolved or rejected.

Syntax

Promise.race(iterableObject);

Example 1

If the iterableObject is empty, then the returned Promise will be “pending” forever and never resolve.

const emptyPromises = [];
Promise.race(emptyPromises).then((result) => {
console.log(result); // Nothing logged to the console
});

Example 2

In the spirit of a race, using setTimeout() within two runners named runnerA and runnerB:

const runnerA = new Promise((resolve, reject) => {
setTimeout(reject, 100, 'The winner is runnerA!');
});
const runnerB = new Promise((resolve, reject) => {
setTimeout(resolve, 300, 'The winner is runnerB!');
});
const promises = [runnerA, runnerB];
Promise.race(promises)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
console.log('Operations for Promise.race() have finished.');
});

Codebyte Example

The following example demonstrates that Promise.race returns a new Promise object which either resolves (if the first settled promise was resolved) or rejects (if the first settled promise was rejected).

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy