JavaScript Promises in LWC

When working with LWC in Salesforce, understanding Promises in LWC is essential for building responsive, asynchronous applications. Promises are useful, especially when handling server calls, APIs or delayed operations.

What is Promise in JavaScript?

Promise is an object that may produce result (completion or failure) of an asynchronous operation sometime in the future. In context of LWC, Promises help in fetching data from server, Loading file from system etc.

function checkIfEven(num){
    return new Promise((resolve, reject) => {
        if(num % 2 === 0){
            setTimeout(() => {
                return resolve("Number is Even");
            }, 1500);
        } else{
            return reject("Number is Odd");
        }
    })
}

checkIfEven(2).then((result) => {
    console.log(result);
}).catch((error) => {
    console.log(error)
})

This basic example illustrates a delayed response when number is even. If you are new to arrow functions or want clearer understanding you might find arrow function post helpful.

MethodsPurposeParametersReturn Value
resolve()Async operation succeedsAny value, object or another promiseA fulfilled Promise with the provided value.
reject()Async operation failsAny value or objectA rejected promise with given reason
then()handles result of a resolved promisecallback functions for resolved and rejected respectivelyA new Promise resolves with return of handlers
catch()called whenever promise rejectedcallback function that takes the rejected reason Returns a promise which is in the pending state
finally()used whenever promise is settled (fulfilled or rejected)callback function with no parametersA promise that resolves/rejects with original value.

States of JavaScript Promises in LWC

Understanding the states of JavaScript Promises in LWC helps in handling operations effectively, consider promises as a placeholder for a value that will be available in future. It can be one of the following states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed with an error.

Chaining with Promise.then() Method

Allows sequential execution of promises, it will pass promise returned from one then() method to next then() method. In LWC, this technique is commonly used when working with multiple imperative Apex calls that need to execute in a specific order.

fetch(<endpoint>).then((result) => {
    return result.json();
}).then((res) => {
    console.log(JSON.parse(res));
})

Promise.all() method

Promise.all() takes an array of promises. It returns a single promise that resolves when all input promises resolve or rejects immediately if any one of the promises rejects.

const promise1 = Promise.resolve("First");
const promise2 = new Promise((resolve) => setTimeout(() => resolve("2nd"),2000));
const promise3 = Promise.resolve("Third");

Promise.all([promise1, promise2, promise3]).then((results) => {
    console.log("All promises resolved: "+results);
}).catch((error) => {
    console.error("One or more promise failed: ",error);
})

Since all three eventually resolve, the .then() block is triggered with All promises resolved: First,2nd,Third

const promise1 = Promise.reject("First");
const promise2 = new Promise((resolve) => setTimeout(() => resolve("2nd"),2000));
const promise3 = Promise.reject("Third");

Promise.all([promise1, promise2, promise3]).then((results) => {
    console.log("All promises resolved: "+results);
}).catch((error) => {
    console.error("One promise failed: ",error);
})

Even though promise2 will succeed, the rejection from promise1 and promise3 causes whole Promise.all() to fail.

Async and Await

async and await keywords are used to handle asynchronous operations in cleaner and readable way than using .then() and .catch()

async: Marks a function as asynchronous. This means it will return a Promise.

await: Can be used only inside async functions to pause the execution of the function until the promise is resolved or rejected.

// Simulate a delayed response using a Promise
function getUserData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ name: 'John Doe', age: 30 });
    }, 2000); // 2 seconds delay
  });
}

// Async function using await
async function showUserData() {
  console.log('Fetching user data...');
  
  try {
    const user = await getUserData();  // Waits until fetchUserData() resolves
    console.log('User Data:', user);
  } catch (error) {
    console.error('Error fetching user data:', error);
  }
}

showUserData();
  • showUserData() is marked as async, so you can use await inside it.
  • await getUserData() pauses execution until the Promise resolves.
  • After 2 seconds, data is logged to the console.

Understanding and using JavaScript Promises in LWC is essential for efficient and clean asynchronous code in Salesforce applications. Whether you’re calling Apex methods, integrating APIs, or handling UI logic, Promises provide a powerful way to manage timing and flow.

You may also like...

Leave a Reply

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