Lightning Web Components – How to Call Async/Await Methods in LWC

lightning-web-components

I have a component to show toast notifications on Salesforce. But the messages should prompt if the first method is undefined. I'm using async/await to try to execute this in order but it's not working.

The code:

    @wire(checkCustomerStatus, { accId: '$recordId'})
    async wiredcheckCustomerStatus  ({ error, data }){
        if(data) {
            this.message = data;
            this.custmStatus = data;
            this.variant = 'error',
            this.dispatchEvent(new CloseActionScreenEvent());
            this.showNotification();
        }
        if(error) {
            console.log('erro status -' + error);
        }
    }
    
    @wire(checkBlockingConditionsOB, { accId: '$recordId' })
    async wiredcheckBlockingConditionsOB ({ error, data }){

        await this.wiredcheckCustomerStatus();
        
        if(this.custmStatus != undefined) {
            
        }
        else {
            if(data) {
                this.message = data;
                this.variant = 'warning',
                this.dispatchEvent(new CloseActionScreenEvent());
                this.showNotification();  
            }
            if(error) {
                console.log('erro status -' + error);
            }
        }

At this point is my mistake:

await this.wiredcheckCustomerStatus();

I'm recieving at console this error:

oneSFA_PlaceOrderButton.js:4 Uncaught (in promise) TypeError: Cannot destructure property 'error' of 'undefined' as it is undefined.

I need that the second @wire block is executed only after the first @wire block.

Any tips?

Best Regards

Best Answer

There is no need of async/await. Once the first wired method returns data, you can call the second apex method imperatively:

@wire(checkCustomerStatus, { accId: '$recordId'})
wiredcheckCustomerStatus  ({ error, data }){
    if(data) {
        this.message = data;
        this.custmStatus = data;
        this.variant = 'error',
        this.dispatchEvent(new CloseActionScreenEvent());
        this.showNotification();
        
        checkBlockingConditionsOB({ accId: this.recordId })
            .then((result) => {
                this.message = result;
                this.variant = 'warning',
                this.dispatchEvent(new CloseActionScreenEvent());
                this.showNotification();  
            })
            .catch((error) => {
                console.log('erro status -' + error);
            });
    }
    if(error) {
        console.log('erro status -' + error);
    }
}
Related Topic