【发布时间】:2016-10-23 01:27:25
【问题描述】:
我在尝试使用 MEAN 堆栈进行异步查询时收到 Callback was already called 错误。我需要第二个回调仅在嵌套查询完成后触发(根据代码中的 cmets)。为什么会出现此错误?
路线示例:
router.route('/teams/:user_id').get(function (req, res) {
TeamProfile.find({
Members : {
$in : [req.params.user_id]
}
}).exec(function (err, teamProfiles) {
var asyncTasks = [];
teamProfiles.forEach(function (teamProfile) {
asyncTasks.push(function (callback) {
UserProfile.find({
UserID : {
$in : teamProfile.Members.map(function (id) {
return id;
})
}
}, function (err, userProfiles) {
teamProfile.Members = userProfiles;
callback();
})
});
});
teamProfiles.forEach(function (teamProfile) {
asyncTasks.push(function (callback) {
Draft.find({
_id : {
$in : teamProfile.Drafts.map(function (id) {
return id;
})
}
}, function (err, drafts) {
teamProfile.Drafts = drafts;
drafts.forEach(function (draft) {
Comment.find({
_id : {
$in : draft.Comments.map(function (id) {
return id;
})
}
}).exec(function (err, comments) {
draft.Comments = comments;
callback();
//This is where the callback should be called
//Throws Error: Callback was already called.
})
})
})
});
});
async.parallel(asyncTasks, function () {
res.json(teamProfiles)
});
});
})
我正在使用async.parallel() 来执行所有查询。我对这一切都很陌生,所以请原谅一些初学者的错误。
【问题讨论】:
标签: node.js mongodb asynchronous mongoose mean-stack