0% found this document useful (0 votes)
25 views6 pages

Using Promise.all in LWC for Async Ops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views6 pages

Using Promise.all in LWC for Async Ops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Salesforce LWC & JavaScript Enthusiasts

[Link]
in LWC
Salesforce LWC & JavaScript Enthusiasts
[Link] is a method that takes an array of promises and returns a
single promise that:
Resolves when all promises in the array are resolved. The resolved
value of the promise returned by [Link] is an array. Each
element in the array corresponds to the resolved value of each
promise in the input array, in the same order

Rejects if any of the promises in the array reject. The returned


promise immediately rejects with the reason of the first promise that
rejects
[Link] is very useful in LWC for handling multiple asynchronous
operations (like fetching data from Apex methods) in parallel ex
getAccounts and getContacts.
By using [Link], you can significantly improve the efficiency of
your components by reducing the wait time for multiple asynchronous
operations.
Salesforce LWC & JavaScript Enthusiasts
EXAMPLE 1 : FETCHING DATA FROM MULTIPLE APEX METHODS AND HANDLING
THEM TOGETHER USING [Link]

let's assume we have two Apex methods: getAccounts and getContacts, which fetch data
from Salesforce. We want to fetch both sets of data in parallel when the component loads

ht
Salesforce LWC & JavaScript Enthusiasts
Explanation
The connectedCallback lifecycle hook
fetches data when the component is
loaded.
[Link] is used to make two
asynchronous Apex calls (getAccounts and
getContacts) concurrently.
The then() block is executed when both
promises resolve successfully, and data is
set in component properties.
The catch() block handles any error if one
of the promises fails
Salesforce LWC & JavaScript Enthusiasts
EXAMPLE 2: PERFORM MULTIPLE INDEPENDENT CALCULATIONS
CONCURRENTLY

sometimes we must perform multiple independent calculations concurrently and wait for
all of them to complete before doing something with the results.

IN THIS Example Three asynchronous calculations are performed using the calculateSquare,
calculateSquareRoot, and calculatePower methods. Each method returns a promise that resolves
after a simulated delay.
Salesforce LWC & JavaScript Enthusiasts

[Link] waits for all three calculations to


complete.
The then() block is executed with the results array
[100, 4, 32] when all promises resolve.
The catch() block will handle any errors if one of the
calculations fails

You might also like