Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Promise.race() Method

  • Last Updated : 13 Sep, 2021
Geek Week

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

 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :