Home > Enterprise >  Promise.race to keep evaluating until it gets a non-rejected promise?
Promise.race to keep evaluating until it gets a non-rejected promise?

Time:12-08

I race requests in my system and want to return whoever is the fastest. However, the fastest promise could also technically throw an error despite the slower promises being successful.

How can I race promises and keep evaluating if the fastest one was a reject?

const myPromises = [p1, p2, p3]
const winner = Promise.race(myPromises) // this fails if winning promise rejects

p1 wins but returns 500 so promise rejects

p2 comes in second with a 200, return p2

CodePudding user response:

You want to use Promise.any() instead.

This will resolve when the first promise you pass it resolves and will ignore rejected promises unless all of them reject (none resolved).

So, if the first two in your example reject immediately, it will wait for the outcome of the third promise.

It sounds like Promise.any() does exactly what you want.

  • Related