Search code examples
promiselwc

promise resolution in imperative APEX call


I have LWCA that calls a method in LWCB (service LWC) that makes an imperative call to an APEX method. The problem is that the promise is not behaving as expected.

LWCA

      import serviceLWC from 'c/servicelwc';

    handleButtonClick() {
       this.apexCallResult = serviceLWC.callApexMethod(parm);
       console.log('lwcA:' + this.apexCallResult );
     }

LWCB

import verify from '@salesforce/apexContinuation/util.verify';

 callApexMethod(parm) {
     console.log('Service lwc');
     verify ({ parm })
            .then(result =>  {
                console.log('lwcB: ' + result);
                return result;
            })
            .catch(error => {
                console.log('lwcB: ' + result);
                return error;
            });
},

console:
Service lwc
lwcA: undefined
lwcB: valid

I expected (maybe incorrectly) that result in lwcB would be resolved before returning the value to the calling fn (lwcA). Can you help me better understand why this isn't working as expected and how I can adjust this code to return a fulfilled promise to the caller?


Solution

  • You need to export a callApexMethod function from LWCB and return another function/promise which return the value of promise resolver - than the this.apexCallResult in LWCA should be equal result from promise. You only need to put some changes on LWCB:

    import verify from '@salesforce/apexContinuation/util.verify';
    
     export function callApexMethod(parm) {
         console.log('Service lwc');
         return verify ({ parm })
                .then(result =>  {
                    console.log('lwcB: ' + result);
                    return result;
                })
                .catch(error => {
                    console.log('lwcB: ' + result);
                    return error;
                });
    }
    

    If you have more functions which need to be exported in LWCB you can use shortcut for export

    function callApexMethodA() {}
    
    function callApexMethodB() {}
    
    export default { callApexMethodA, callApexMethodB }