[URGENT] How to return promise function inside promise function


#1

I know that topic’s title is not clear. Maybe with an example…

constructor() {
    this.methodA().then((result) => {
        alert(result); // must alert "A" or "B"
    });
}

methodA() {
    return new Promise((resolve) => {
        let someExpressionResult:boolean = false;
        if(someExpressionResult) {
            setTimeout(() => {
                resolve('A');
            }, 500)
        } else {
            return this.methodB(); // This is not working now!
        }
    });
}

methodB() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('B');
        }, 500)
    });
}

In the code above, if someExpressionResult is set to true, we can see an alert with ‘A’ message.
Otherwise, if someExpressionResult is set to false, we can not see any alert. MethodA never ends.

How can I get it working?

Thanks in advance!


#2

It’s not working because if someExpressionResult is falsy then the new Promise you return in methodA never calls resolve.

What you want is probably

        } else {
            this.methodB().then(result => resolve(result));
        }

but your logic seems a bit convoluted.

(I have a video explaining Promises here if that helps.)