1

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');

3

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

  • Okay, so you're saying if I use await for this.apex1,this.apex2,this.apex3 then it will be sequential? – sfdc07 Sep 15 '20 at 11:18
  • Yes.. IT will wait till first method finishes execution – Pranay Jaiswal Sep 15 '20 at 11:38
  • Wow.. It is working as expected now.. This is Awesome.. Thank you so much..!! – sfdc07 Sep 15 '20 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.