Avi Rai
Using async/await to call Apex method imperatively
Hello everyone,
We know that there are two methods to call an Apex method from a Lightning Web Component:
Wire Apex Methods to Lightning Web Components
Call Apex Methods Imperatively
When calling apex methods imperatively in LWC, we mainly go for promises. Well, there is one more cleaner style which is the async function and await keyword that allows us to do the same asynchronous behavior.
async function - An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style. An async function can contain zero or more await expressions.
async function foo() {
return 1
}
Scenario
Below, I am getting the list of accounts present in my org with a click of a button and then displaying them using a lightning-datatable base component.
Firstly, I have simply created a button "Get Accounts" and a table in the HTML file.
<template>
<lightning-card title="async/await" icon-name="custom:custom4">
<lightning-layout class="slds-p-around_small">
<lightning-layout-item size="12">
<lightning-button label="Get Accounts" onclick={handleClick}></lightning-button>
</lightning-layout-item>
</lightning-layout>
<!-- Accounts table-->
<div class="slds-p-around_small">
<lightning-datatable
data={data}
columns={columns}
key-field="Id"
hide-checkbox-column="true"
show-row-number-column="true"
>
</lightning-datatable>
</div>
</lightning-card>
</template>
And here goes the JS controller.
import { LightningElement } from "lwc";
import getAccounts from "@salesforce/apex/AccountController.getAccounts";
const columns = [
{ label: "Name", fieldName: "Name" },
{ label: "Industry", fieldName: "Industry" }
];
export default class AsyncAndAwait extends LightningElement {
data = [];
columns = columns;
async handleClick() {
try {
const accounts = await getAccounts();
this.data = accounts;
} catch (error) {
console.error(error);
}
}
}
While writing the function "handleClick", we have to use the async keyword.
async handleClick() {
}
After that, we have to call the apex method by using await keyword which tells the Javascript engine that we want to wait for the function getAccounts to be executed before executing the subsequent lines. Code after await expression can be thought of as existing in a .then callback. For handling errors, we need to use the try/catch block instead of .catch() function.
async handleClick() {
try {
const accounts = await getAccounts();
this.data = accounts;
} catch (error) {
console.error(error);
}
}
Well, that's it. Yeah, that's it.
Hope you liked it. Open to any suggestions. Stay safe and healthy! Thanks :)