I have the following code. I expected that the 'core exception' could be caught by the 'immediately executed function (see the end)' and printed out "Got it in main scope", but it was not executed as expected, that is, "Got it in main scope" is not printed.
'use strict'; function core() { function wrapper() { return new Promise((resolve, reject) => { throw new Error("wrapper exception rises"); }); } return new Promise(async (resolve, reject) => { try { await wrapper(); } catch(error) { console.error(error.message); throw new Error("core exception rises"); } }); } (async function() { try { await core(); } catch(error) { console.error(error.message); console.error("Got it in main scope"); } })();
The program running result is
wrapper exception rises (node:10093) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: core exception rises (node:10093) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Who can help explain? Thank you so much!
I am using node v7.2.1
A simplified example is this:
Change:
or:
The problem with your code is that
core exception rises
ThePromise
in this place has neitherresolve
norreject
, so what do you do? ^^Why can I get the expected results only by making the following modifications? Is it related to microtask? Can anyone help explain it clearly?
The result of the operation is: