[SalesForce] Chaining async apex calls in LWC

In my LWC Component, I want to chain my apex callouts. Meaning, first ApexCall 1 should happen then apex Call 2 should happen and so on. So, for that, I am using JS Promises chaining method like below:

chainApexCalls(){

    doApexCalls({
            ..
        })
            .then(() => {
                alert('Call Apex 1');
                this.apex1();
            })
            .then(() => {
                alert('Call Apex 2');
                this.apex2();
            })
            .then(()=>{
                alert('Call Apex 3');
                this.apex3();
            })
            .catch(error => {
                
            });

}


apex1(){
    doApex1Callout({
            ..
        })
        .then(() => {
                alert('Apex Call 1 finished');
            })
}

apex2(){
    doApex2Callout({
            ..
        })
        .then(() => {
                alert('Apex Call 2 finished');
            })
}

In this, as soon as the alert('Call Apex 1'); is called, I am expecting next alert to be alert('Apex Call 1 finished'); but the issue is that the alert('Call Apex 2') is called first and then alert('Apex Call 1 finished'); is called.

Is there any way that I can chain these async Apex calls?

Expected Output should be : 1. alert('Call Apex 1'); 2. alert('Apex Call 1 finished'); 3. alert('Call Apex 2'); 4. alert('Apex Call 2 finished'); 5. alert('Call Apex 3');

Best Answer

then block only ensures this.apex1(); , this.apex2();, this.apex3(); that the method is called in order. But there is no order when it gets executed.

apex1() contains an async method. the async method will execute independently.hence you are getting the behavior.

Have a look at https://javascript.info/async-await

async/await functions in LWC

Related Topic