JavaScript .race()
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).
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- A full-stack engineer can get a project done from start to finish, back-end to front-end.
- Includes 51 Courses
- With Professional Certification
- Beginner Friendly.150 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours