Lightning Web Component

A Guide about LWC Async Await

The async/await keywords in Lightning Web Components are crucial in managing asynchronous processes.

They allow you to wait for a task to be completed before moving on to the next one.

LWC Async Await

LWC Async Await Basics

Async keyword

Let's start with the async keyword. If you add this keyword to a Javascript function, it will return a Promise, an asynchronous action that will return a success value or failure reason.

For example, when you want to make async the onclick function of a lightning-button.

async handleClick(){

}

Also, this is how to declare a normal Javascript function with the async keyword.

async function handleClick(){

}

Finally, here is how you would do it if you want to include the async on an arrow function.

const handleClick = async() => {
  
}

Await keyword

After declaring a function async, the code execution can be paused until the task is completed using the await keyword. The await keyword can only be used if the function is async.

async handleClick(){
    const data = await this.getAccount(this.recordId) // WAIT UNTIL THIS FINISH
    if(data.result === 'ok'){ // PROCEED WITH THE LOGIC

    }
}

LWC Async Await Use Cases

Here are a few use cases where you can use the async/await keywords on your Lightning Web Component.

API Request

If you need to connect your Lightning Web Component with other APIs outside of Salesforce, you can use async/await to fetch that API and get the expected data.

async fetchData(){
    const result = await fetch('https://api.example.com/data');
    const data = await result.json();
    console.log(data);
}

Database Operations

To utilize Apex controllers inside a Lightning Web Component for database operations, one can use async/await keywords to wait for the execution of the Apex method.

To call the Apex controller you will need to do it imperative to be able to add async/await

async handleSave(){
    await getAccounts()
        .then(data => {
            console.log(data);
        })
        .catch(error => {
            console.error(error);
        });
}

File Uploads

If you allow users to upload files or attachments, you can use async/await to handle file uploads and ensure that the upload process doesn't interfere with other component functionality.

async uploadFile(){
    const fileData = new FormData();
    fileData.append('file', this.selectedFile);

    const result = await uploadFileController({ fileData });
}