Search code examples
javascriptasynchronousasync-awaittry-catch

Catching errors from async function in try...catch block outside of async function


So I'm doing a tutorial which contains a part about asynchronous JavaScript. I feel like I have it down pretty good, but it includes this section which I feel like is wrong for catching errors?

    async function myFunction {
      // ...
      await someObject.methodThatReturnsPromise();
      // ...
      await aFunctionThatReturnsPromise();
      // ...
    }
    
    try {
      // ...
      myFunction();
      // ...
    } catch (e) {
     // error handling code
    }

This is the explanation it gives.

You can see how this works in the example below. myFunction() is an asynchronous function that is called within a try...catch block. When myFunction() is run, code execution is paused at methodThatReturnsPromise() until the promise resolves, at which point the code continues to aFunctionThatReturnsPromise() and waits again. The code in the catch block runs if an error is thrown in the asynchronous function, and this will happen if the promise returned by either of the methods is rejected.

My understanding is this is all incorrect? To catch errors, either put the try...catch block inside myFunction(), or catch the errors the when calling myFunction() in the global context with

myFunction().catch((error) => console.log(error));

Solution

  • You are correct regarding the code and quoted "explanation":

    • The await operator will throw with the rejection reason if a promise it is waiting on becomes rejected.

    • An async function will reject the promise it returns when called if an uncaught exception is thrown when executing its function body.