首页 > 解决方案 > 承诺 then() 和 catch() UnhandledPromiseRejectionWarnin

问题描述

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 进行测试。

标签: javascriptnode.jsecmascript-6

解决方案


d.then()创建一个由于被拒绝而被拒绝的新承诺d。那是没有正确处理的被拒绝的承诺。

您应该链接.then.catch不是:

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

推荐阅读