May 4, 2023

TypeScript - Promise.race()

The Promise.race() static method takes an iterable of promises as input and returns a single Promise. This returned promise settles with the eventual state of the first promise that settles (either fulfilled or rejected).

It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).

Lets see an example:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 300, 'promise1 value');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'promise2 value');
});

Promise.race([promise1, promise2]).then((value) => {
     // promise2 is faster, so the 'value' will be the result of promise2
   console.log(value);
});

Output will be :

promise2 value

In this example, both promises will get resolved, but since the promise2 is faster (with less waiting time), the Promise.race() method will return promise2, it is the first promise in the input list which get settled (rejected or resolved).

If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to the first of these values found in the iterable.

See this example:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'promise1 rejected');
});

const promise2 = new Promise((resolve, reject) => {
  reject('promise2 rejected');
});

Promise.race([promise1, promise2])
.then((value) => {
  console.log(value);
})
// promise2 is already settled (rejected), 
// so the 'error' will be the rejection-error of promise2
.catch((error) => { console.error(error);})
;

Output will be :

promise2 rejected

Since promise2 is already settled (rejected), Promise.race() method will return promise2.

References:

Related Post(s):

No comments:

Post a Comment