运行代码
Promise.all(new Promise((res, rej) => rej('Failure!')))
.catch(() => console.log("It's all okay."))
在 Node v12.19.0 中将日志记录It's all okay.
到控制台,但仍会引发异常。这是为什么?我会期待与我跑步时相同的行为
new Promise((res, rej) => rej('Failure!'))
.catch(() => console.log("It's all okay."))
这也将记录It's all okay.
到控制台,但不会引发异常。
如何在 Promise.all() 中捕获拒绝?
完整的控制台输出:
> Promise.all(new Promise((res, rej) => rej('Failure!'))).catch(() => console.log("It's all okay."))
Promise { <pending> }
> It's all okay.
(node:2872) UnhandledPromiseRejectionWarning: Failure!
(node:2872) 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: 4)
> new Promise((res, rej) => rej('Failure!')).catch(() => console.log("It's all okay."))
Promise { <pending> }
> It's all okay.