Latest Code Tutorials

Javascript Promise Race Example | Promise.race() Tutorial

0 87

Get real time updates directly on you device, subscribe now.

Javascript Promise Race Example | Promise.race() Tutorial is today’s topic. The Promise.race() method returns the promise that resolves or rejects as soon as one of the promises in an iterable resolves or rejects, with the value or reason from that promise. If the iterable passed is empty, the promise returned will be forever pending. If the iterable contains one or more non-promise value and an already resolved/rejected promise, then Promise.race() method will resolve to the first of these values found in the iterable.

Javascript Promise Race Example

The syntax for Javascript Promise.race() method is following.


An iterable parameter is an object, such as an array.

The Javascript Promise Race Example is following.

// app.js

const p1 = Promise.resolve(21);
const p2 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
	}, 1000);

Promise.race([p1, p2]).then(values => { 

In the above example, the p1 promise is resolved synchronously whereas p2 promise resolved asynchronously. So, when the Promise.race() function is start executing, the race between p1 and p2 promise has also been started and whichever resolves first, will return in the output.

In the above example, the p1 promise is synchronous and takes no time in resolving, that is why we will get the 21 in the output.


Javascript Promise Race Example | Promise.race() Tutorial

This method is only implemented because it’s in the ES6 standard. If you want to race promises to fulfillment the .any() method is more appropriate as it doesn’t qualify a rejected promise as the winner. It also has fewer surprises: .race() must become infinitely pending if an empty array is passed but passing an empty array to .any() is more usefully a RangeError.

Finally, Javascript Promise Race Example | Promise.race() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.