2025-05-19 11:09:14

Promise.all vs Promise.allSettled in LWC

Promises are a fundamental part of JavaScript, allowing us to handle asynchronous operations in a clean and manageable way. In the context of Lightning Web Components (LWC), promises are especially useful since much of the interaction with Salesforce data and APIs relies on asynchronous operations.

While dealing with multiple asynchronous tasks simultaneously, two very common methods are used to manage promises : Promise.all() and Promise.allSettled(). Both of these methods provide ways to handle multiple promises, but they behave differently when one or more promises fail. Understanding these differences and knowing when to use each one is critical for writing robust and efficient LWC code.

In this blog, we will dive deep into Promise.all() and Promise.allSettled(), explaining their differences, usage, and implementation within LWC.

Problem Statement 

In a Salesforce application, performance and responsiveness are critical especially when multiple backend operations are required to support a single user action. Imagine this common scenario: when a user loads a dashboard or submits a form, the system needs to fetch customer records, process data through custom logic, and update a related record, all simultaneously.

Naturally, to ensure a fast and smooth experience, these tasks are executed asynchronously and in parallel. But here’s the problem : What happens if just one of those tasks fails?

If the system is not designed to handle such failures gracefully, one failing task can break the entire process. This can lead to incomplete data being shown, errors appearing on the user interface, or even critical operations being skipped entirely. In this results is lost productivity, poor user experience, and potential data inconsistencies.

This is where Promises come into the picture.

When managing multiple asynchronous tasks, developers often use Promise.all() to run them in parallel. While it's fast and efficient, it’s also unreliable. If one task fails, everything fails.

The alternative is Promise.allSettled(), which waits for all tasks to complete, regardless of whether they succeeded or failed, allowing the application to handle each result individually.

By using Promise.allSettled(), enhances your system’s stability by preventing a single failure from disrupting the entire workflow. This approach helps ensure the system is robust, user-friendly, and capable of gracefully managing real-world uncertainties.

Where We Are Using Promise.all() and Promise.allSettled() in LWC

In LWC, we often interact with Salesforce services using the @wire service, Apex methods, or other APIs. However, many times we need to perform multiple asynchronous tasks in parallel, especially when making HTTP requests, calling multiple Apex methods, or querying multiple resources.

Both Promise.all() and Promise.allSettled() are suitable for these scenarios. But each method handles promise rejections differently, which makes them useful in different situations.

Example Scenario

Let’s consider the following scenario: Suppose you want to retrieve several pieces of data from Salesforce. You need to fetch a list of accounts, contacts for each account, and user details.

If you use Promise.all(), your code will wait for all promises to resolve. However, if one promise fails, the entire operation fails.

On the other hand, if you use Promise.allSettled(), the code waits for all promises to complete, regardless of whether any of them failed, allowing you to handle each promise’s result individually.

How to Implement Promise.all() and Promise.allSettled() in LWC

1) Using Promise.all() in LWC

Promise.all() is used when you want to wait for all promises to resolve or reject. It resolves when all promises have successfully resolved, but if any promise is rejected, it will immediately reject with the first error encountered.

🔁 Workflow of Promise.all()

Example Implementation

Let’s say we have two promises: fetching account data and fetching contact data. We want both to succeed before proceeding.

import { LightningElement, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import getContacts from '@salesforce/apex/ContactController.getContacts';

export default class PromiseAllExample extends LightningElement {
    accounts;
    contacts;
    error;
    
    connectedCallback() {
        this.fetchData();
    } 
    
    fetchData() {
      Promise.all([
          getAccounts(),
          getContacts()
      ])
      .then(([accounts, contacts]) => {
         // Process all data if all promises succeed
          this.accounts = accounts;
          this.contacts = contacts;
      })
      .catch((error) => {
          // Handle the error gracefully
          this.error = error;
          console.error('Error:', error);
      });
  }
}    

Explanation

  • Promise.all([getAccounts(), getContacts()]): Executes both Apex calls in parallel, improving performance by not waiting for one to complete before starting the other.

  • Then block (.then(([accounts, contacts]) => { ... })): If both promises resolve successfully, the returned results are destructured and assigned to the accounts and contacts properties of the component.

  • Catch block (.catch((error) => { ... })): If either of the promises fails, this block is triggered. The error is captured and stored in the error property, and also logged to the console for debugging.

This is a "fail-fast" approach. If even one promise fails, the entire Promise.all() operation fails, and none of the successful results will be processed.

2) Using Promise.allSettled() in LWC

Promise.allSettled() allows you to wait for all promises to settle, regardless of whether they resolve or reject. It provides an array of objects with information about the result of each promise (either fulfilled or rejected).

🔁 Workflow of Promise.allSettled()

Example Implementation

  • Promise.allSettled([getAccounts(), getContacts()]): Executes both Apex calls in parallel and waits for all of them to settle whether they succeed or fail.

  • Then block: Once all promises have settled, the .then() block receives a results array. Each item in this array is an object with: 

  1. status: either 'fulfilled' or 'rejected'

  2. value: the resolved value if successful.

  3. reason: the error if it failed.

  • The .catch() block catches any unexpected errors that may occur while executing the promises (for example, if there's an error in the function or the promises themselves are not set up correctly). This will log any unhandled errors to the console.

  • Result Handling: The code loops through each result:

  1. If it's fulfilled, it assigns the data to the corresponding property (accounts or contacts).

  2. If it's rejected, it logs the error to the console without breaking the entire operation.

Difference Between Promise.all() and Promise.allSettled()

Feature Promise.all() Promise.allSettled()
Behavior on failure Rejects immediately when one promise fails Waits for all promises to settle, regardless of failure.
Return value Returns an array of resolved values if all promises are successful. Returns an array of objects representing the status and value/reason of each promise.
Use case Use when you require all promises to succeed for the operation to be considered successful. Use when you need to perform multiple operations and want to handle success/failure of each individually.
Error handling Global error handling in the .catch() block. Individual handling for each promise’s result.
Performance impact Can be faster since it stops as soon as a failure occurs. Slightly slower since it waits for all promises to complete, regardless of their outcome.

Use Cases

Use Cases for Promise.all()

🔗 All Data Must Succeed
Use when all asynchronous tasks must complete successfully for your operation to proceed.
Promise.all() fails fast. if any one promise is rejected, the whole operation fails.

🧩 Dependent or Batch Tasks
Use when tasks rely on each other or must all complete together.
Example: Load user profile, preferences, and settings—all required to render the page.

Use Cases for Promise.allSettled()

🎯 Partial Success is Acceptable
Use when you're okay with some data failing while still using the rest.
Example: Fetch accounts, contacts, and leads—if one fails, display the others.

🛠️ Independent Tasks
Use for unrelated async operations that you want to handle individually.
Example: Logging events, analytics updates, and data refreshes that don’t depend on each other.

Get In Touch

Bring your business to life.


Get in touch with our expert Salesforce consultants to streamline your business processes and maximize efficiency.

What Happens Next :
    • 1We schedule a call at your convenience
    • 2We do a discovery and consulting meting
    • 3We prepare a proposal