未处理的承诺拒绝async.js瀑布内的警告
问题描述:
我正在使用令人惊叹的async.js库进行项目。试图了解承诺的使用,但我不能。未处理的承诺拒绝async.js瀑布内的警告
我实现下面的代码:
function connect(){
return new Promise(function (resolve, reject) {
bar.getConnection(server, function(err, conn){
if(err) {
reject("An error. " + err);
}
else{
resolve("Ok. Connected to: " + conn.serverAddress);
}
});
});
}
然后在async waterfall
:
exports.getRequest = function(callbk){
(function(callback) {
async.waterfall([
function (next) {
connect().then(function (result) {
console.log(result);
next();
}).catch(function (e) {
// If something gets an error on the next function, this catch fires
// And the 'next(e)' does not execute
console.log("An error here");
next(e);
});
},
function (next) {
// do something .... and get a result
// but if something gets an error here, fires the 'catch' on 'connect'
next(null, result);
},
function (err, result) {
if(err) {
callback(true, "" + err);
}
else {
callback(false, result);
}
}
]);
})(function(error, result) {
callbk(error, result);
});
}
但是,如果事情在第二功能得到错误的“瀑布”第一的catch
内功能上升,它附带:
(node:8984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
(node:8984) [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.
我知道使用Promise和async.js并不是一个好主意,但我想明白为什么。
我已经看到几个相同的答案,但我仍然无法解决它。
答
我知道这不是一个好主意,用承诺与async.js
好!
但我想明白为什么。
如果任何在你的回调(包括一个传递给getRequest
)的一个人扔从then
回调next();
通话异常,承诺会拒绝。不仅如此,拒绝承诺的catch
也会执行,现在调用next(e);
- 这将使async.js抱怨next
回调被调用两次,忽略e
并拒绝第二个承诺,并发生新的异常。此拒绝不会在任何地方处理,并会记录到您的控制台。
看一看在difference between .then(…, …)
and .then(…).catch(…)
- 如果你使用的是前者,那么原来的异常将拒绝承诺,并得到记录为未处理的,没有回调被调用两次:
connect().then(function (result) {
console.log(result);
next(null, e);
}, function (e) {
console.log("An error here");
next(e);
});
请勿混用的承诺, 'async.js'模块,使用一个。 – alexmac
您展示的代码对我来说看起来很不错,您确定,它是您收到拒绝警告的正确位置吗? –
@JohannesMerz是的。我已经测试过,那就是这个地方。我相当确定。 – robe007