Tuesday, 23 May 2017

Error being thrown within async function gets caught

I want to use an async function instead of returning a promise, however to reject I need to throw an error like this:

async function asyncOperation() {
  throw new Error("Terminate this application.");
}

(async () => {
  try {
    await asyncOperation();
  } catch (e) {
    console.error(e);
  }
  console.log("Nope, I am still running!"); // This will be printed regardless
})();

This means that to catch the reject I must put the function call within a try statement. By doing this, instead of terminating the application, I catch the error and I can continue afterwards.

This of course works as you would expect however I want to throw an error to actually terminate the application regardless if the function was called within a try statement or not.

How could I achieve this without checking the error within the catch statement?



via Wilco Bakker

No comments:

Post a Comment