0

Sorry if question label is frustrating. I am calling lwc method and do some actions on then and inside that lwc I there are apex method. But it gives me error on then inside "firstMethod". I have tried async and it didn't help

Error: Cannot read properties of undefined

firstMethod() { 
    this.secondMethod(true, true).then((result) => {
        console.log(result);
    })
}

secondMethod(boolVar1,boolVar2) {
    if(boolVar2){
        apexMethod({boolVar:boolVar}).then((resp)=> {
            return resp;
            //Promise.resolve(resp) doesnt work too
        })
    } else {
       return Promise.resolve(true);
    }
}

I have added "return apexMethod" and it works

1
  • Hi. Please edit the question to add the specifics of the error (full error text).
    – Phil W
    Commented Nov 30, 2022 at 14:05

1 Answer 1

0

The issue is that secondMethod returns a value if boolVar2 is true and a Promise if not. The return type should always be the same.
Calling an apex method imperatively returns a Promise, that's why you handle it with .then(), so you can just return it, without handling:

secondMethod(boolVar1, boolVar2) {
    if(boolVar2){
        return apexMethod({boolVar: boolVar});
    }
    return Promise.resolve(true);
}

I removed the else since it's unnecessary.

2
  • Thanks, but is it possible to just do 'return Promise.resolve(resp)' in second method? Doesnt work for me, but i need to do more logic here.
    – fedove
    Commented Nov 30, 2022 at 14:13
  • @fedove The answer is yes, but why would you need a one-line method that just return Promise.resolve(true);? It would return a promise, so whoever calls that method must handle it via then() or with async/await. Could you please add more details?
    – RubenDG
    Commented Nov 30, 2022 at 15:11

You must log in to answer this question.

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