top of page
  • Writer's pictureAvi 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


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.

	<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>
		<!-- Accounts table-->
		<div class="slds-p-around_small">

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(); = accounts;
		} catch (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(); = accounts;
	} catch (error) {

Well, that's it. Yeah, that's it.

Hope you liked it. Open to any suggestions. Stay safe and healthy! Thanks :)

10,943 views0 comments

Recent Posts

See All

What is Modal? A modal overlays a popup on top of the current app window. This paradigm is used in cases such as the creation or editing of a record, as well as various types of messaging and wizards.

What are Platform Events? Platform events are the event messages (or notifications) that your apps send and receive to take further action. They simplify the process of communicating changes and respo

Post: Blog2_Post
bottom of page