异步查询的NodeJS和处理结果 [英] async nodejs querying and processing results
问题描述
我从MongoDB的拍摄对象的数组。数组中的每一个元素是一个后,与笔者为USER_ID。现在,我希望能够找到相关的USER_ID用户的信息。
I have an array of objects taken from mongodb. Every element in the array is a post, with author as user_id. Now i wish to find the user info related to the user_id.
由于节点使用异步方法找到从数据库中的数据,foreach循环完成回调之前完成。
Since node uses async methods to find the data from db, the forEach loop finishes before the callbacks finish.
docs.forEach(function(doc, index){
//get the user for this doc
User.find({_id: mongo.BSONPure.ObjectID(doc.user_id)}, {name: 1, username: 1, email: 1}).skip(0).limit(1).toArray(function(err, user){
user = user[0]
if(err) {
throw new Error(err)
} else {
docs[index].user = user
if(doc.for_id) {
User.find({_id: mongo.BSONPure.ObjectID(doc.for_id)}, {name: 1, username: 1, email: 1}).skip(0).limit(1).toArray(function(err, for_user){
for_user = for_user[0]
if(err) {
throw new Error(err)
} else {
docs[index].for_user = for_user
}
})
}
}
})
})
因此,在这个循环结束,如果我发送一个CB(文档),文档不具备用户和for_user属性。我该如何克服呢?
So at the end of this loop, if i send a cb(docs), docs do not have the user and for_user attribute. How do I overcome this?
推荐答案
使用Node.js语言编写的 步骤。它将在串行顺序运行功能
Use Step for node.js. It will run your functions in serial order
var Step = require('step');
Step( docs.forEach(...), function() { cb(docs); } );
或者,如果你知道记录的总数,可以调用回调,当你处理完最后一个。事情是这样的。
Or if you know the total number of records, you can call the callback when you're done processing the last one. Something like this
var count = docs.count(); // or something
var processed = 0;
docs.forEach(... if (++processed == count) cb(docs); );
这篇关于异步查询的NodeJS和处理结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!