Promise then() 和 catch() UnhandledPromiseRejectionWarning

问题描述 投票:0回答:1

当我运行这个简单的代码时,我得到了

UnhandledPromiseRejectionWarning

var d = new Promise((resolve, reject) => {
  if (false) {
    resolve('hello world');
  } else {
    reject('no bueno');
  }
});

d.then((data) => console.log('success : ', data));

d.catch((error) => console.error('error : ', error));

完整的回复是:

error :  no bueno
(node:12883) UnhandledPromiseRejectionWarning: no bueno
(node:12883) 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:12883) [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. 

看起来

d.catch()
正在被解雇。我注意到,如果注释掉
d.then()
,警告消息就会消失。

我从终端调用脚本,如

node foobar.js

我做错了什么吗?

在 MacOS High Sierra 下使用节点 v8.14、v10 和 v11 进行测试。

javascript node.js ecmascript-6
1个回答
4
投票

d.then()
创建了一个被拒绝的新 Promise,因为
d
被拒绝了。这就是未正确处理的被拒绝的 Promise。

您应该改为链接

.then
.catch

d
  .then((data) => console.log('success : ', data))
  .catch((error) => console.error('error : ', error));
© www.soinside.com 2019 - 2024. All rights reserved.