Promise抛出“未处理的承诺拒绝”的奇怪行为错误 [英] Weird behavior with Promise throwing "Unhandled promise rejection" error

查看:538
本文介绍了Promise抛出“未处理的承诺拒绝”的奇怪行为错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Node运行此代码时,它会在控制台中抛出 Unhandled promise rejection 错误(甚至显示错误已捕获 text first)。

When I run this code using Node, it throws an Unhandled promise rejection error in the console (even showing the error caught text first).

const promise = new Promise((resolve, reject) => setTimeout(reject, 1000))
promise.then(() => console.log('ok'))
promise.catch((e) => console.log('error caught'))

然而,当我将 catch 方法链接到然后方法,错误消失:

Nevertheless, when I chain the catch method to the then method, the error disappears:

const promise = new Promise((resolve, reject) => setTimeout(reject, 1000))
promise.then(() => console.log('ok')).catch((e) => console.log('error caught'))

这不是第一个应该处理拒绝的代码吗?

Isn't the first code supposed to handle the rejection?

我还尝试了Chrome中的第一个代码,如果我在新标签页(或google.com)中打开检查程序,它就可以运行。如果我在任何其他页面(如stackoverflow.com),它会抛出异常。对此有何解释?这对我来说真的很奇怪!

I also tried the first code in Chrome and it works if I open the inspector when I'm in a new tab (or google.com). If I'm in any other page (like stackoverflow.com) it throws the exception. Any explanation to this? This seems really weird to me!

推荐答案

为了被视为处理,被拒绝的承诺应与<$ c $同步链接c>然后(...,...)(2个参数)或 catch(...)

In order to be considered handled, rejected promises should be synchronously chained with then(..., ...) (2 arguments) or catch(...).

promise.then(()=> console.log('ok'))是一个没有链接的单独的承诺 catch(...),因此被拒绝的承诺将导致未处理的拒绝。

promise.then(() => console.log('ok')) is a separate promise that wasn't chained with catch(...), so rejected promise will result in unhandled rejection.


如果我在任何其他页面(如stackoverflow.com)它会抛出异常

If I'm in any other page (like stackoverflow.com) it throws the exception

这不是例外,它不会阻止脚本正常运行。处理未处理的拒绝的方式取决于 Promise 实现。在默认情况下,Chrome实施会导致未捕获(在承诺中)控制台错误。

This isn't an exception, it doesn't prevent a script from running normally. The way unhandled rejections are treated depends on Promise implementation. Chrome implementation results in Uncaught (in promise) console error by default.

它没有出现在某些地方Chrome中的网站意味着网站设置了 unhandledrejection 事件处理程序,用于抑制错误输出。

That it doesn't appear on some websites in Chrome means that a website set up unhandledrejection event handler that suppresses error output.

这篇关于Promise抛出“未处理的承诺拒绝”的奇怪行为错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆