How to Return as Soon as the First JavaScript Promise Settles?

Starting with ES12, you can use the Promise.race() method to return as soon as one of the promises fulfills or rejects. It would return a Promise that resolves to the value from the first settled promise.

For example, consider the following:

// ES12+
const p1 = new Promise(function(resolve, reject) {
    setTimeout(() => reject(new Error('one')), 500);
});
const p2 = new Promise(function(resolve, reject) {
    setTimeout(() => resolve('two'), 100);
});

Promise.race([p1, p2]).then(function(value) {
    console.log(value); // 'two'
});

In the example above, p2 resolves first, therefore, the Promise.race() method returns a Promise that resolves to the value from that Promise (i.e. "two").

Carrying on from the same example, if you switch things around and make p1 resolve first, then it would result in a rejected Promise as shown in the following example:

// ES12+
const p1 = new Promise(function(resolve, reject) {
    setTimeout(() => reject(new Error('one')), 100);
});
const p2 = new Promise(function(resolve, reject) {
    setTimeout(() => resolve('two'), 500);
});

Promise.race([p1, p2]).then(function(value) {
    console.log(value);
}).catch(function(err) {
    console.log(err.message); // 'one'
});

Hope you found this post useful. It was published . Please show your love and support by sharing this post.