【发布时间】:2021-06-19 06:44:12
【问题描述】:
运行代码
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.
【问题讨论】:
-
Promise.all()的参数应该是一组承诺,而不是一个承诺。 -
Promise.all(ARRAY_OF_PROMISE_HERE) -
谢谢。我认为
Promise.all(promise1, promise2, ...)应该工作的假设是错误的。但是为什么即使它不是一个数组,它也会触发拒绝? -
也许使用
.catch((err) => console.log(err))而不是说“没关系。”:-P -
未处理的拒绝来自
new Promise((res, rej) => rej('Failure!')),它没有在任何地方处理,而不是来自Promise.all()(您处理处理)。
标签: javascript es6-promise unhandled-promise-rejection