我正在尝试对mongo数据库执行批处理操作。其思想是遍历每个用户,然后找到正在学习相同课程或上同一所大学的其他用户,并存储有关这些匹配项的信息。
所有内容都包含在这样的循环中:
User.find({}, function(err, doc){
doc.forEach(function(candidate){
//other find operations in here
...
}
}
其中“user”是在网站上注册的用户的集合。我遇到的问题是foreach循环正在为每个用户分派所有回调,而我希望等待foreach循环中的所有回调完成,然后再转到下一个文档。
我试过使用async,但我似乎无法理解这一点。
如何一次处理一个用户?
最佳答案
您可以使用async
来实现这一点,例如async.eachSeries
:
async.eachSeries(doc, function (candidate, cb) {
//other find operations in here
...
// and you call cb() once they're done (important!)
// or call cb('some error') if it failed
}, function (err) {
if (err) {
// this means that some cb() above was called with error
} else {
// here all candidates are processed successfully
}
});
见:https://caolan.github.io/async/docs.html#eachSeries