我有下一个代码:
exports.getCommunities = function(user, callback)
{ //I am getting the communities for a user.
community_users.find({'user':user}).sort({_id : 1 }).toArray(function(err, docs) {
docs.sort
var clas = [];
//for each community, I need to find the country of that community and add it to each docs object. To do so, i call a getCommunityByName function that finds the community document in the communities mongodb collection by a given name.
docs.forEach(function(entry,i) {
clas.push(entry);
getCommunityByName(entry.name, function(e, o){
if (o){
clas[i].country = o.country;
if (docs.length-1 == i) {callback(null,clas)}
} else { console.log('community-not-found: '+entry.name)}
});
});
});
};
我的行为很奇怪。想象一下,docs是一个7对象数组。我正在获得一个7位阵列,但是随机数有阵列。有时只有3个有国家/地区密钥,有时是5个,有时是6个......
我认为调用回调的if语句不是等待每次调用getCommunityByName而我不知道为什么......
我需要一些亮点...
此致
答案 0 :(得分:1)
假设getCommunityByName
执行异步请求,可能是对最终项目的请求在某些先前项目之前返回,因此它很快就会调用回调。而不是使用循环中的i
来决定何时回拨,而是倒计时返回的请求并在它们全部完成时调用回调:
exports.getCommunities = function(user, callback)
{ //I am getting the communities for a user.
community_users.find({'user':user}).sort({_id : 1 }).toArray(function(err, docs) {
docs.sort
var clas = [];
//for each community, I need to find the country of that community and add it to each docs object. To do so, i call a getCommunityByName function that finds the community document in the communities mongodb collection by a given name.
//initialise counter to number of items
var counter = docs.length;
docs.forEach(function(entry,i) {
clas.push(entry);
getCommunityByName(entry.name, function(e, o) {
//request returned, decrement counter
counter--;
if (o){
clas[i].country = o.country;
} else { console.log('community-not-found: '+entry.name)}
if (counter == 0) {
//All requests returned, fire callback
callback(null, clas);
}
});
});
});
};