我粘贴了两个几乎相同的代码,但略有不同,一个工作正常,但另一个给出UnhandledPromiseRejectionWarning。
async function promise () {
return new Promise((resolve, reject) => {
throw new Error();
resolve();
reject();
})
}
promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('from the catch')});
输出是:
> node index.js
from the catch
但是对于这种情况
function promise () {
return new Promise(async (resolve, reject) => {
throw new Error();
resolve();
reject();
})
}
promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('err')});
输出是这样的
> node index.js
(node:98195) UnhandledPromiseRejectionWarning: Error
at /home/parthiv/Projects/exp/index.js:47:11
at new Promise (<anonymous>)
at promise (/home/parthiv/Projects/exp/index.js:46:10)
at Object.<anonymous> (/home/parthiv/Projects/exp/index.js:53:1)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:98195) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:98195) [DEP0018] 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.
有人可以在 promise 中解释异步函数的这种行为吗?