Skip to content
Related Articles

Related Articles

JavaScript Promise.race() Method

Improve Article
Save Article
  • Last Updated : 31 May, 2022
Improve Article
Save Article

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

We may think of this particular method as in the form of a real life example where several people are running in a race whosoever wins comes first wins the race, same scenario is here, which ever promise successfully fulfills or rejects at early will be executed at first and rest ones results will not be display as an output.

Syntax:

Promise.race(iterable);

Parameters:

  • iterable: An iterable object such as Array, Map, String, etc. having several different promises in them.

Example 1:

Javascript




<script>
const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 600, "one");
});
 
const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 200, "two");
});
 
Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
});
</script>

Output: As promise2 was faster so it prints its own result which is two.

two

Example 2:

Javascript




<script>
const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve("five"), 500);
});
 
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("six")), 100);
});
 
Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
});
<script>

Output: As promise2 is faster than promise1, so it rejects and doesn’t print anything.

Supported Browsers: 

  • Google Chrome 32 and above
  • Edge 12 and above
  • Mozilla Firefox 29 and above
  • Opera 19 and above
  • Safari 8 and above
  • Internet Explorer not supported

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!