DEV Community

Siyi Le
Siyi Le

Posted on

Promise.allSettled() and Promise.any()

Sometimes when we work on a front-end app and need to call backend API multiple times for user. And we may have another requirement here is that it should stop at any successful request.

const promise1 = axios.get(url1)
const promise2 = axios.get(url2)
const promise3 = axios.get(url3)

// some codes check promise
// ...

But problem here is

  1. It won't stop when we made any successful request.
  2. Code looks ugly, if we add some logic deal with resolve and reject.

We cannot use Promise.all(), since it will immediately reject if any promise is rejected

Best solution here should be using Promise.any(), it will resolve first successful request, and raise AggregateError if all rejected.

const promise1 = axios.get(url1)
const promise2 = axios.get(url2)
const promise3 = axios.get(url3)

const promises = [promise1, promise2, promise3]

const response = await Promise.any(promises)
// do something...

However, Promise.any() is available in ES2021 and supported after Chrome 85 beta. Unfortunately, we can't use it right now.

Another alternative (not elegant) solution is using Promise.allSettled(). It will respectively solve and reject every promises.

const promise1 = axios.get(url1)
const promise2 = axios.get(url2)
const promise3 = axios.get(url3)

const promises = [promise1, promise2, promise3]
const results = await Promise.allSettled(promises)
results.forEach((result) => {
  if (result.status === 'fulfilled') {
    const { value } = result
      // do something..
  } else { // results.status === 'rejected'
    const { reason } = result
    // do something...
  }
}

Code above is dumb :(
Wish we can get native support from our browser soon.

Top comments (2)

Collapse
 
ayabongaqwabi profile image
Ayabonga Qwabi

What about using Promise.all?

Collapse
 
siyile profile image
Siyi Le

Promise.all will reject if any promise in group is rejected. It may not what we want.