尽管抓住了承诺,但未处理的承诺拒绝 [英] Unhandled promise rejection despite catching the promise

查看:62
本文介绍了尽管抓住了承诺,但未处理的承诺拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白......是我还是节点中的错误?

I don't understand... Is it me or is this a bug in node?

这符合预期:

const a = new Promise((resolve, reject) => {
  setTimeout(() => reject('timeout'), 1000);
});
a.catch(console.log);

这是一个警告:

const a = new Promise((resolve, reject) => {
  setTimeout(() => reject('timeout'), 1000);
});
a.then(console.log);
a.catch(console.log);

我明白

timeout
(node:40463) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): timeout
(node:40463) [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.

推荐答案

使用带有承诺的 .then(...) 会返回一个新的承诺(称为 链接).因此,当您执行以下操作时:

Using .then(...) with a promise returns a new promise (that's called chaining). Therefore, when you do something like:

a.then(console.log); // line 1 creates a new promise "b"
a.catch(console.log); // line 2 handles rejection on promise "a"

其中 a 是您的初始承诺,您将在第 1 行创建一个新承诺(不再是 a.我们称之为b).因此,即使您将 .catch(...)a 一起使用,您也不会处理 b 上的拒绝,这解释了您在控制台上看到的消息.

where a is your initial promise, you're creating a new promise on line 1 (one that is not a anymore. let's call it b). So even though you're using .catch(...) with a, you're not handling the rejection on b, which explains the message you're seeing on console.

为了避免这个消息,你应该添加一个 .catch(...) 到这个新的 promise b,在第 1 行

To avoid this message, you should add a .catch(...) to this new promise b, on line 1

这篇关于尽管抓住了承诺,但未处理的承诺拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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