我有下一个代码:
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 个位置数组,但其中随机数量的数组具有国家/地区 key 。有时只有 3 个有国家/地区 key ,有时是 5 个,有时是 6 个...
我认为调用回调的 if 语句不会等待每次调用 getCommunityByName 并且我不知道为什么......
我需要一些光线......
问候,
最佳答案
假设 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);
}
});
});
});
};
关于Javascript 奇怪的行为,异步问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742092/