JavaScript Promise race: The Complete Guide

0
16
Javascript Promise.race() example tutorial

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.

Javascript Promise Race

Javascript Promise race() is an inbuilt function that returns the promise that resolves or rejects as soon as one of the promises in the 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 values and an already resolved/rejected promise, then the Promise.race() method will resolve to the first of these values found in the iterable.

Syntax

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

Promise.race(iterable);

Parameters

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

The Javascript Promise Race Example is the following.

// app.js

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

Promise.race([p1, p2]).then(values => { 
	console.log(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, it 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 useful than a RangeError.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

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