0

I'm new on JS code and i have a problem. I created two lwc components, parent and child. In child component there's a public method decorated with @api. I can call this method from parent and pass some parameters, including a method.

CHILD COMPONENT

import { LightningElement,track,api } from 'lwc';
import apexMethod from '@salesforce/apex/TestClass.apexMethod';

export default class Parent extends LightningElement {

@api type = '';
@api message = '';

buttonClick(event) {

    let obj = {
        confirmButtonMethod : this.callMethod
    }
    this.template.querySelector('c-popup-error').setMethod(obj);

}

callMethod = () => {
    apexMethod({}).then(result => {
    console.log('test callMethod');
    //do same logic
    });
}

PARENT COMPONENT JS

    @api
    setMethod(obj) {

       this.confirmMethod = obj.confirmButtonMethod;    
   };

   confirmClick(event) {
      console.log('enter confirmClick');
      this.confirmMethod();
      console.log('exit confirmClick');
  }

PARENT COMPONENT HTML

<template>
<lightning-button label="Confirm" variant="brand" onclick={confirmClick}></lightning-button>
</template>

When I click on parent component button result is:

>enter confirmClick
>exit confirmClick 
>test callMethod

My question is: how to obtain correct execution order like this?

>enter confirmClick
>test callMethod
>exit confirmClick

Thanks for your help

1 Answer 1

0

The apex call returns a Promise, so there's a round-trip to the server, and a corresponding delay. To get the desired order, you need to wait for the return value:

   async confirmClick(event) {
      console.log('enter confirmClick');
      await this.confirmMethod();
      console.log('exit confirmClick');
  }

Likewise, callMethod must also be async:

async callMethod = () => {
    let result = await apexMethod({});
    // Do some logic
    return result;
}
2
  • Thanks for your help. how i should if i wanted to make my child component generic? Let me explain: in my example i passed an apex method call to child component, in other case i could have a simple function and then no promise like your example, there's a way to block execution of this.confirmMethod() until is processed? Or a way to convert on child component callback function into promise? Thanks and sorry if I wrote nonsense
    – fraoud
    Apr 21, 2020 at 15:00
  • @fraoud If the method is not asynchronous, it will still work with this framework. If it is asynchronous but not a Promise, it should first be converted to a promise. There's a decent blog post that explains how to do this (not my blog post).
    – sfdcfox
    Apr 21, 2020 at 15:44

You must log in to answer this question.

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