.race()
Anonymous contributor
Anonymous contributor3077 total contributions
Anonymous contributor
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).
All contributors
- Anonymous contributorAnonymous contributor3077 total contributions
- BrandonDusch580 total contributions
- karel.de.smetoutlook.com7 total contributions
- christian.dinh2481 total contributions
- Anonymous contributor
- BrandonDusch
- karel.de.smetoutlook.com
- christian.dinh
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.