Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Promise.race() Method

  • Last Updated : 13 Sep, 2021

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.

Syntax:

Promise.race(iterable);

Parameters:

  • iterable: An iterable object such as Array, Map, String, etc.

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 it prints 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 6.0 and above
  • Internet Explorer 9.0 and above
  • Mozilla 4.0 and above
  • Opera 11.1 and above
  • Safari 5.0 and above

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :