Blog / WordPress/ Promise.all vs Promise.allSettled: When to Use Each

Promise.all vs Promise.allSettled: When to Use Each

The Core Difference

The fundamental difference comes down to how they handle failures:

Promise.all - Fails fast. If any promise rejects, the entire operation fails immediately.

Promise.allSettled - Never fails. It waits for all promises to complete, regardless of whether they succeeded or failed.

Think of it like this: Promise.all is an "all-or-nothing" approach, while Promise.allSettled is a "let me know how everything went" approach.

Understanding Promise.all Behavior

Promise.all takes an array of promises and returns a single promise that resolves to an array of results. Here is the key behavior:

const promises = [
  fetch("/api/user"),
  fetch("/api/posts"),
  fetch("/api/comments")
];

const results = await Promise.all(promises);
// If ALL succeed, results = [userData, postsData, commentsData]
// If ANY fails, the entire Promise.all REJECTS immediately

This fail-fast behavior is useful when you need all operations to succeed for your code to make sense.

When Promise.all Breaks Your Code

Here is where developers get into trouble. If fetchOrders() fails but fetchUser() and fetchRecommendations() succeeded, you have lost perfectly good data just because one thing went wrong.

Enter Promise.allSettled

Promise.allSettled was introduced in ES2020 specifically to solve this problem. It waits for ALL promises to complete:

const results = await Promise.allSettled([
  fetchUser(),
  fetchOrders(),
  fetchRecommendations()
]);

// results looks like:
[
  { status: "fulfilled", value: userData },
  { status: "rejected", reason: Error },
  { status: "fulfilled", value: recommendationsData }
]

Decision Matrix

Scenario Use Promise.all Use Promise.allSettled
All tasks required Yes No
Independent tasks, partial success OK No Yes
Loading screen Yes No
Dashboard with independent widgets No Yes

Summary

Use Promise.all when you need ALL promises to succeed. Use Promise.allSettled when you are firing off multiple independent operations and want to know the outcome of each one.

Post a Comment

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