gpt4 book ai didi

javascript - 浏览器是否仍然默默地吞下未处理的拒绝 promise ? Node 呢?

转载 作者:数据小太阳 更新时间:2023-10-29 04:43:20 25 4
gpt4 key购买 nike

有很多建议建议您确保不要让任何被拒绝的 promise 得不到处理。如果你不这样做,建议警告,错误将永远不会被注意到,并将被完全吞没。控制台不会打印任何内容。

这个建议似乎已经过时了。当未处理被拒绝的 promise 时,现代浏览器和现代版本的 Node 似乎确实会打印警告。拿这段代码:

async function thisIsGoingToFail() {
await Promise.reject();
console.log('this should not print, as the line above should error');
}

async function main() {
await thisIsGoingToFail();
}

main();

如果你在 Node 中运行它,你将得到:

(node:20760) UnhandledPromiseRejectionWarning: undefined
(node:20760) 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(). (rejection id: 2)
(node:20760) [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.

标准建议是源代码的最后一行应该看起来像这样,以避免吞噬错误:

main().catch(err => { console.err(err) });

但看起来并不像需要的那样。所以这是我的问题:

  • 现代浏览器和现代 Node 是否总是会针对未处理的拒绝 promise 显示警告?什么版本号的实现支持这个?
    • (请注意,浏览器不必支持事件 unhandledrejection 以便在未处理 promise 时打印警告。)
  • 我们是否需要确保拥有顶级 catch 功能,就像您经常被建议的那样,或者让实现显示警告是否同样有用?

最佳答案

大多数现代实现会在未处理被拒绝的 promise 时向控制台打印警告,但不是全部:

  • Node.js 从版本 6.6.0 开始(参见 changelog ):

    promises: Unhandled rejections now emit a process warning after the first tick. (Benjamin Gruenbaum) #8223

    在未来的版本中,未处理的 promise 拒绝将以非零退出代码终止 Node.js 进程。

  • Firefox 确实显示警告,但我无法找到第一个这样做的版本。 MDN docs这么说:

    We adopt the following strategy: if a promise is rejected at the time of its garbage-collection and if the promise is at the end of a promise chain (i.e. thatPromise.then has never been called), then we print a warning.

    Note: This warning is generated some time after the error occurred, and may provide less information about the error location. It generally indicates the need to insert a proper error handler. When a proper rejection handler is used, it effectively replaces this delayed reporting.

  • Chrome 确实显示警告,但我还是找不到说明哪个版本是第一个执行此操作的文档。 Chrome >= 49 更进一步,支持 unhandledrejection event ,它允许您添加自定义事件处理程序来处理所有未处理的被拒绝的 promise 。

  • Safari 也显示警告,并且由于版本 >= 11,还支持 unhandledrejection 事件。

  • Edge 好像还不支持,基于这个open GitHub issue in Microsoft/ChakraCore .

所以看起来大多数现代浏览器(Edge 除外)确实会针对未处理的拒绝显示警告,但没有明确的文档保证会显示警告,或者会立即显示警告。处理 unhandledrejection 事件对于支持它的浏览器来说似乎是个好主意。


tldr; 在撰写本文时,似乎最好的做法是仍然使用 catch 来处理顶级被拒绝的 promise 处理程序(以避免在 Edge 中吞噬错误并终止 Node 中的进程)。对于 Chrome 和 Safari,利用 unhandledrejected 事件可能很有用。

关于javascript - 浏览器是否仍然默默地吞下未处理的拒绝 promise ? Node 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52061394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com