UnhandledPromiseRejection警告即使有承诺

时间:2018-09-25 15:19:40

标签: javascript node.js error-handling

我有以下无法解决的问题。这是我的代码:

//file1.js
module.exports = {
delete: function(id) {
    return new Promise((resolve,reject) => {

      setTimeout(() => {reject('bla bla');}, 2000);

       });
  }
}


//file2.js 

const file1 = require('file1');
var delPr = file1.delete(id);

    delPr.then(() => {
      console.log('+++++++++++++++++++++++++++');
      res.status(200).json({
        message : "delete post"
      });});

    delPr.catch((error) => {

      console.log('-----------------------------');
}

这是我得到的代码:

-----------------------------
(node:102437) UnhandledPromiseRejectionWarning: bla bla
(node:102437) 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: 1)
(node:102437) [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.

将file2.js中的代码更改为:

file1.delete(id).then(() => {
  console.log('+++++++++++++++++++++++++++');
  res.status(200).json({
    message : "delete post"
  });}).catch((error) => {

  console.log('-----------------------------');
  });
});

一切正常,我只能在控制台中看到'--------',有人可以解释一下有什么区别吗?我没有看到一个,并且在过去3个小时里一直在看。

1 个答案:

答案 0 :(得分:1)

.then()返回一个承诺,并且该承诺没有得到处理。

因此,当您执行a.then().catch()时,该承诺的拒绝由捕获来处理