承诺拒绝错误 - 未处理拒绝错误:已关闭

时间:2016-01-18 15:10:40

标签: javascript node.js promise bluebird

我使用以下代码检查某些应用程序端口当前它的工作情况但我在第三个else语句中出错

Unhandled rejection Error: Port is not open

我该怎么处理? 我用蓝鸟

checkPortStatus: function(port, host){
  return new Promise((resolve, reject) => {
    portscanner.checkPortStatus(port, host, function(error, status) {
      if(error)
        reject(error);
      else if(status === 'open')
        resolve(status);
      else
        reject(new Error('Port is not open'));
    });
  });
},

2 个答案:

答案 0 :(得分:1)

最终,您需要处理被拒绝的承诺,例如使用.catch()

obj.checkPortStatus(port, host).then((status) => {
  ...
}).catch((err) => {
  // handle the error here...
});

答案 1 :(得分:1)

调用checkPortStatus的代码的属性会导致未处理的异常。

该代码可能看起来像

somePromiseFunction()
.then(checkPortStatus(port, host))
.then(someOtherPromiseFunction())

它会(最低限度地)"处理"如果它看起来更像是

的例外
somePromiseFunction()
.then(checkPortStatus(port, host))
.catch(function(error) {
  console.log(error.message);
})
.then(someOtherPromiseFunction()

在这方面您的代码存在问题:使用resolvereject时,使用return也是必要的。因此,使用resolve()代替return resolve();与reject相同。

附注,如果有帮助:在我添加return后,代码中的每个else语句前面都会有一个return。您可以删除else语句。

祝你好运!

相关问题