【发布时间】:2015-01-05 11:50:02
【问题描述】:
我正在使用 Async 实用程序模块从 Mongodb 数据库中返回项目。我想异步进行。我在尝试退货时遇到问题。
我想在所有User.find()'s 完成后触发回调,现在async.each() 正在提前终止,并且只在它应该全部返回时从数据库中给我一个项目。
代码如下:
async.each(lessons, function(lesson, next) { // For each item in lesson array
if (_.isEmpty(lesson.lesson_grades) == true) { // Check if the grades array is empty
return;
} else {
async.each(lesson.lesson_grades, function(grade, next) { // For each grade in grade array
User.find({ // Find user from grade user_id
_id: grade.user_id,
}, '-salt -hashedPassword', function(err, user) {
grade["name"] = user[0].name; // Add name
grade["email"] = user[0].email; // Add email
next(); // !! I think this is where the problem lies, it fires next() once the first item has been returned - so it doesn't get to the other items !!
});
}, function(err) {
next(lessons);
});
}
}, function(lessons, err) {
return res.json(200, lessons); // Return modified lessons (with name and email) to browser, currently only returns one but returns them all if a setTimeout() is added, making it a premature callback problem
});
有人可以为我指出正确的方向吗?我应该跟踪迭代吗?任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js mongodb asynchronous