Call Apex methods synchronously in LWC

by Rijwan Mohmmed
call-apex-methods-synchronously-in-lwc-techdicer

Hello folks, welcome to my blog. Today we will discuss Call Apex methods synchronously in LWC. We can call the Apex method in LWC in two ways, i.e. Imperative and wire. It will always be easy for us when we have only call single method a time. But what about when we call a series of apex methods at a single call? these methods will run asynchronously if you call them as it is. But we can call these methods one after one by the use of async & await.

Also check this: Add Lightning Flow in LWC

call-apex-methods-synchronously-in-lwc-output-techdicer
call-apex-methods-synchronously-in-lwc-output-techdicer

Key Highlights :

  1. Can call the Apex method in chaining.
  2. Can get a response from the first call of Apex then call the second method.
  3. We handle this by the use of Promise chaining.
  4. We use async and await in our methods so it waits for the first apex call response and then calls the second method.

Code :

AccountDataController.cls :

public class AccountDataController {

    @AuraEnabled (cacheable=true)
    public static List<Contact> fetchContacts(){
        return [SELECT Id, Name, AccountId, Email, LeadSource, MobilePhone, Phone FROM Contact LIMIT 15];       
    }
    
    @AuraEnabled(Cacheable = true)
    public static List<Account> getAccounts(){
      return [SELECT Id, Name, Industry, Type, Phone, Rating, AccountNumber FROM Account ORDER BY Name LIMIT 10];
    }
}

asyncLWC.HTML:

<template>
     <!------Header------->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Call Apex methods synchronously in LWC Salesforce </span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!------/Header------->


    <lightning-card title="Call Apex methods synchronously in LWC Salesforce" icon-name="standard:opportunity">
        <div class="slds-var-p-around_small"> 
            <lightning-button label="Call Apex Method" onclick={handleApexCall}></lightning-button>
        </div>
    </lightning-card>
</template>

asyncLWC.JS:

import { LightningElement } from 'lwc';
import fetchContacts from '@salesforce/apex/AccountDataController.fetchContacts';
import getAccounts from '@salesforce/apex/AccountDataController.getAccounts';

export default class AsyncLWC extends LightningElement {
    async handleApexCall() {
        console.log('Before first method call');
        let data = await this.handleFirstCall();
        console.log(data);
        console.log('After first method call and Before second method call');
        let data2 = await this.handleSecondCall();
        console.log(data2);
        console.log('After second method call');
    }


    handleFirstCall() {
        return fetchContacts()
            .then((result) => {
                return result;
            })
            .catch((error) => {
                console.log(error);
            });
    }

    handleSecondCall() {
        return getAccounts()
            .then((result) => {
                return result;
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

asyncLWC.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>54.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

call-apex-methods-synchronously-in-lwc-output-techdicer
call-apex-methods-synchronously-in-lwc-output-techdicer

Reference :

  1. async & await
What’s your Reaction?
+1
0
+1
0
+1
1
+1
0
+1
1
+1
0

You may also like

Leave a Comment