2016-01-18 93 views
0

我用下面的代码来检查一些应用程序端口currenlty它的工作,但我在第三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')); 
    }); 
    }); 
}, 

回答

1

最后,你需要处理拒绝的承诺,例如使用.catch():代码调用checkPortStatus的

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

属性导致未处理的异常。

该代码可能看起来像

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 s我提到,代码中的每个else语句都立即以return开头。您可以删除else语句。

祝你好运!

+1

不需要添加'return'(参见[示例代码](http://bluebirdjs.com/docs/api/new-promise.html)),但我确实认为它会使代码有点结构化。 – robertklep

+0

@robertklep感谢分享。这在过去可能有所不同;我很欣赏这些信息。知道这一点,我会清理一下我的代码。 – BaldEagle

相关问题