The Weekly Dev

Developer News & Tutorials

Est. 2024  ·  Vol. I
The Weekly Dev

When to use Promise.allSettled() and how is it different from Promise.all()?

Would you want to launch multiple Promises and wait until ALL of them have finished, but not lose resolved ones if some fail? Promise.allSettled() is what you need.

VA

By Vasili Zalimidis

When to use Promise.allSettled() and how is it different from Promise.all()?

We can use Promise.all() to wait for multiple promises to resolve before going on with our code.

But there is a small problem. When we use Promise.all(), if one of the promises is rejected because of an error, we lose the data from all the other promises that successfully fulfilled and returned data.

const responses = await Promise.all([
  getPosts(),
  getUsers(),
  getShops(),
  getPrices()
]).catch(console.error);

for (const response of responses) {
  console.log(response.data);
}

But what if we want to keep the data from the resolved promises?

That's where Promise.allSettled() comes into play.

const responses = await Promise.allSettled([
  getPosts(),
  getUsers(),
  getShops(),
  getPrices()
]).catch(console.error);

for (const response of responses) {
  if (response.status === 'rejected') continue;
  console.log(response.value);
}

Promise.allSettled() fires when all promises have been fulfilled or rejected — it never short-circuits. We then use if (response.status === 'rejected') continue to skip the failed ones and process the rest, keeping their results in the process.

Summary

| Method | Behaviour on rejection | |---|---| | Promise.all() | Rejects immediately, all data lost | | Promise.allSettled() | Waits for all, partial results available |

Use Promise.all() when all results are required and a single failure should abort everything. Use Promise.allSettled() when you want the best available result even if some promises fail.

← Back to Front Page