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

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

问题描述

当我使用 Node 运行这段代码时,它会在控制台中抛出一个 Unhandled promise denied 错误(甚至首先显示 error catched 文本).

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 方法链接到 then 方法时,错误消失了:

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!

推荐答案

为了被认为被处理,被拒绝的 promise 应该与 then(..., ...) (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')) 是一个单独的 promise,没有与 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 实现会导致 Uncaught (in promise) 控制台错误.

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天全站免登陆