【问题标题】:UnhandledPromiseRejectionWarning even when there is a .catch on promise [duplicate]UnhandledPromiseRejectionWarning 即使有 .catch on promise [重复]
【发布时间】:2018-09-25 23:21:43
【问题描述】:

我有以下我无法弄清楚的问题。这是我的代码:

//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 个小时里一直在看它。

【问题讨论】:

  • delPr.then(…)的返回值与delPr不一样
  • 你能详细说明吗???你说then 子句被击中了,那为什么我看不到++++ 打印???
  • 我并不是说调用了实现回调。我说.then() 方法调用本身返回的不是delPr,这就是你没有看到的区别
  • .then() 仅在执行时调用,还是我错了?
  • 所有这些,在某个时候。您可能想阅读文档,了解在哪些情况下 then/catch 返回的承诺会被履行/拒绝。

标签: javascript node.js error-handling


【解决方案1】:

.then() 返回一个承诺,但该承诺未被处理。

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

【讨论】:

  • 我不明白,reject 不是按照最初的承诺工作吗? delPr??如何解决承诺并输入then clouse 并被catch 捕获?
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 2019-06-17
  • 2016-05-31
  • 2018-04-10
  • 2018-03-20
  • 1970-01-01
  • 2018-06-14
  • 2019-02-24
相关资源
最近更新 更多