4

I am busy working with some code that is responing in an unexpected way (to me). It involves handling Node.js promise exceptions.

I have the following function modified so that all it does is fail

function asynFunc() {
    return new Promise(function(res, rej) {

        rej("GENERIC ERROR");

    });
}

The problem comes in when I am trying to call it and handle this error. If I do the following it works as I expect it to, the function fails and executes the catch which returns, stopping the last console log from executing

async function appStart() {

    try {
        await asyncFunc();
    } catch(log) {
        console.log(log);
        return;
    }

    console.log("YOU SHOULD NOT SEE THIS");

}

appStart();

If I write the function as follows though, it does not seem to return, it still executes the last console log regardless of the await

async function appStart() {

    await asyncFunc().catch(function(log) {
        console.log(log);
        return;
    });

    console.log("YOU SHOULD NOT SEE THIS");

}

If this is doing what I think it's doing then the return is returning from the function inside of the catch and not the appStart function itself, or I'm completely wrong in which case I have no idea why it's not returning.

Is there a way to use the second catch method and still have it return from the calling function?

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106

2 Answers2

5

In the second example, you are not returning from the outside function in the catch, you are returning from the catch callback:

await asyncFunc().catch(function(log) {
    console.log(log);//  ^
    return;          //  | returns from that function
});

This has the effect of catching the error and moving on and returning a new promise resolving to undefined. There is no way to control the return of the outside function from inside the callback. You need to test the result of the async operation from the outside function, which leaves you with try/catch or explicitly testing the result after the promise resolves.

Mark
  • 90,562
  • 7
  • 108
  • 148
2

You're right. It's returning only inside the catch callback, not the outer async function. That's why it exits the catch callback and resolves, and then logs "YOU SHOULD NOT SEE THIS". Generally, it's very unreadable if you mix promise then and catch chaining along with async/await and try/catch. Pick one and stick with it, because mixing them may lead to the inability to catch and handle errors seamlessly.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143