This is a part of The Promises in Javascript series. In the last part of the series we discussed Promise.all, today we’ll talk about Promise.race and when to use it.

Have you been a part of a race before, remember those sports event in school and all?

Yea, that’s what it’s 😀 . Think no more. Just one person wins in a race of 100 athletes, right?
Exactly. Only the person that wins the race goes home with the price whether the officials like them (gets resolved) or not (gets rejected).

Promise.race is an async function that takes in an array of promises and returns a promise if one of the promises is rejected or resolved. It returns the one that first gets settled first (whether rejected or resolved), it returns the reason for the rejection if one gets rejected.

It’s very similar with the Promise.all because they both receive the same values — an iterable of promises. The difference is in the returned value.

Here is an example:

Here we have 4 promises in an array.

const athlets = [
  new Promise((resolve, reject) => setTimeout(resolve, 222, '🥝')),
  new Promise((resolve, reject) => setTimeout(resolve, 333, '🍓')),
  new Promise((resolve, reject) => setTimeout(resolve, 111, '🍍')),// the new girl
  new Promise((resolve, reject) => setTimeout(resolve, 444, '🍇')
]

When you run this with Promise.race the one with a the lowest time 111 will be settled first, right? That’s because the time it takes for it to run and return a result is way shorter than the others.

const athlets = [
  new Promise((resolve, reject) => setTimeout(resolve, 222, '🥝')),
  new Promise((resolve, reject) => setTimeout(resolve, 333, '🍓')),
  new Promise((resolve, reject) => setTimeout(resolve, 111, '🍍')),// the new girl
  new Promise((resolve, reject) => setTimeout(resolve, 444, '🍇')
]

Promise
.race(athletes)
.then((result)=>{
  console.log(result) // all will be resolved but pineaple '🍍` will be returned because it will be resolved first.
})
.catch((error)=>{
  console.log(error)
})

That’s really it.

What if one is rejected? The promise will be exited with just that error.

So, deciding which one to use between Promise.all, Promise.allSettled, or Promise.race depends on the return value you want.

Cheers,

PSS: If you want to see the implementation of the Javascript Promises, like how the magic works under the hood you can check the Chromium Repository on GitHub. Don’t be scared.

Stay safe.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *