1

运行代码

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.
4

1 回答 1

2

正如Bergi在评论中指出的那样......

如果您在没有 catch 语句的情况下执行您的第一段代码(或实际打印您捕获的错误),您将看到发生了什么。

Promise.all(new Promise((res, rej) => rej('Failure!')))

回报:

Promise {<rejected>: TypeError}
Uncaught (in promise) Failure!
Uncaught (in promise) TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
    at Function.all (<anonymous>)
    at <anonymous>:1:9

请注意,第一个错误是我们通过拒绝承诺而引发的错误。

第二个错误来自未Promise.all()正确使用,这是您遇到的错误。

由于Promise.all()方法使用不正确,我们通过拒绝 promise 引发的错误永远不会被捕获。


现在,让我们在一个数组中使用我们的 Promise 测试代码,这是Barmar在评论Promise.all()中指出的正确用法。

Promise.all([new Promise((res, rej) => rej('Failure!'))])
    .catch(() => console.log("It's all okay."))

回报:

Promise {<fulfilled>}
It´s all okay.

所以,我们成功地捕捉到了被拒绝的承诺错误。

另外值得注意的是,最终返回的 promise 是catch()方法执行后返回的 promise。自从我们成功执行了 catch 语句以来,这已经实现了,尽管Promise.all()实际返回的 Promise 被拒绝了。

于 2021-03-23T07:25:27.950 回答