8

I have two methods seen below, the first method is a wired call:

    @wired (firstMethodCall, {param1: 'test'})
    wiredResult(result){
        console.log('1');
        this.secondMethodCall();
        console.log('5');
    }

   secondMethodCall(){
       console.log('2');
       imperativeApexCall({param1: 'test'})
       .then(result => {
           console.log('3');
        });
        console.log('4');
    }

When the wired call runs, The console logs in the following order:

1
2
4
5
3

I want it to run sequentially to print:

1
2
3
4
5

How can I make sure the imperative apex call has fully completed executing before the line "console.log('5')" in the wired call runs?

2
  • we cant see how you are invoking your methods, additionally, you can chain promises to execute your methods sequentially
    – glls
    May 21, 2020 at 18:18
  • @glls I have edited the question, the first method call is a wired call so it runs when I navigate to a page with the component. May 21, 2020 at 18:23

1 Answer 1

10

You would use async/await, as in:

@wire (firstMethodCall, {param1: 'test'})
async wiredResult(result){
    console.log('1');
    await this.secondMethodCall();
    console.log('4');
}

async secondMethodCall(){
    return new Promise(async (resolve, reject) =>{
        console.log('2');
        var result = await imperativeApexCall({param1: 'test'});
        console.log('3');
        resolve(result);
    });
}
5
  • what if imperativeApexCall does throw error from apex.
    – Pratap M
    Apr 11, 2023 at 14:55
  • @PratapM You can use try-catch to catch any Apex error: new Promise(async (resolve, reject) => { console.log('2'); try { var result = await imperativeApexCall({ param1: 'test' }); console.log('3'); resolve(result); } catch (e) { reject(e); } });
    – sfdcfox
    Apr 11, 2023 at 15:15
  • can we try like below ::: @wire (firstMethodCall, {param1: 'test'}) async wiredResult(result){ console.log('1'); try{ console.log('2'); var result = await imperativeApexCall({param1: 'test'}); console.log('3'); } catch(e){ console.log(e);} console.log('4'); } All I did is removed secondaryMethodCall method
    – Pratap M
    Apr 11, 2023 at 15:39
  • @PratapM Yes, but don't use var result, it will clash with the parameter from the wire method. Instead, use a different name, and prefer let or const, as var is subject to variable hoisting.
    – sfdcfox
    Apr 11, 2023 at 15:46
  • obviously....i did not notice...Thanks for the minor details also checking. :)
    – Pratap M
    Apr 11, 2023 at 15:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .