Javascript 回调已经被称为异步并行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27521471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Callback was already called async parallel
提问by sazap10
Hi I am trying to use the Async module to retrieve two users and do some processing after they have both been retrieved however I keep getting the error message: Callback was already called. Below is the code i currently have:
嗨,我正在尝试使用 Async 模块来检索两个用户并在它们都被检索后进行一些处理,但是我不断收到错误消息:回调已被调用。以下是我目前拥有的代码:
app.get('/api/addfriend/:id/:email', function(req, res) {
var id = req.params.id;
var friendEmail = req.params.email;
async.parallel([
//get account
function(callback) {
accountsDB.find({
'_id': ObjectId(id)
}, function(err, account) {
console.log(id);
if (err || account.length === 0) {
callback(err);
}
console.log(account[0]);
callback(null, account[0]);
});
},
//get friend
function(callback) {
accountsDB.find({
'email': friendEmail
}, function(err, friend) {
console.log(friendEmail);
if (err || friend.length === 0 || friend[0].resId === undefined) {
callback(err);
}
console.log(friend[0]);
callback(null, friend[0].resId);
});
}
],
//Compute all results
function(err, results) {
if (err) {
console.log(err);
return res.send(400);
}
if (results === null || results[0] === null || results[1] === null) {
return res.send(400);
}
//results contains [sheets, Friends, Expenses]
var account = results[0];
var friend = results[1];
if (account.friends_list !== undefined) {
account.friends_list = account.friends_list + ',' + friend;
}
else {
account.friends_list = friend;
}
// sheetData.friends = results[1];
accountsDB.save(
account,
function(err, saved) {
if (err || !saved) {
console.log("Record not saved");
}
else {
console.log("Record saved");
return res.send(200, "friend added");
}
}
);
}
);
});
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Alexander T.
Add elsestatement to your code, because if you get error, your callback executes twice
将else语句添加到您的代码中,因为如果出现错误,您的回调将执行两次
if (err || account.length === 0) {
callback(err);
} else {
callback(null, account[0]);
}
回答by ctindel
The docs from async actually say:
Make sure to always return when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases.
提前调用回调的时候一定要始终返回,否则很多情况下会导致多次回调和不可预知的行为。
So you can do:
所以你可以这样做:
return callback(err);

