Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Promise race() Method

JavaScript Promise race() Method

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, the same scenario is here, which ever promise is successfully fulfills or rejects at early will be executed at first and rest one’s results will not be displayed 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: This example shows the basic use of the Promise.race() method in Javascript. As promise2 was faster so it prints its own result which is two.

Javascript




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);
});


Output

two

Example 2: This example shows the basic use of the Promise.race() method in Javascript. As promise2 is faster than promise1, so it rejects and doesn’t print anything.

Javascript




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);
});


Output: 

Uncaught (in promise) Error: six

We have a complete list of Javascript Promise Methods, to check those please go through the Javascript Promise Complete Reference article.

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

RELATED ARTICLES

Most Popular

Recent Comments