Javascript 奇怪的行为,异步问题?

标签 javascript

我有下一个代码:

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/

相关文章:

javascript - 在不存在的时间间隔上调用clearInterval() 会有什么后果吗?

关闭浏览器之前的 JavaScript 警告未按预期工作

javascript - 使用 jQuery 插入 HTML 的最简单方法

javascript - 重新加载页面时 localStorage 返回未定义

javascript - 如何从异步调用返回响应?

javascript - 有没有更优雅的方式来编写这个循环?

javascript - knockout 错误 : Cannot find closing comment tag to match

javascript - 无法编译;使用 grunt 响应图像找不到有效的源文件

javascript - query 选择未被点击的div增加其宽度

javascript - 在 jQuery timeago.js 中本地化字符串