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 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

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

Promise.race(iterable);

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.

#javascript #promise.race #js

Javascript Promise Race Example | Promise.race() Tutorial
2.25 GEEK