This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                            
                                (6个答案)
                            
                    
                3年前关闭。
        

    

我正在尝试使用猫鼬模式从多个集合中检索数据,然后以JSON格式发送回响应。这是我编写的代码。

function GetConnections_V2(req,res){

    Connection.find({"user_id":"55006c36c30f0edc5400022d"})
     .exec(function(err,connections){

        var list = [];
        var obj = new Object();
        connections.forEach(function(connection){
                           obj.friend_id = connection.user_id_friend;
          User.findById(connection.user_id_friend)
          .exec(function(err,user){
                    if(user !== null) {

                            obj.friend_email = user.email;
                            obj.friend_details_id = user.details;
        UserDetail.findById(user.details).exec(function (err, details) {
                                    obj.firstname = details.firstname;
                                    obj.lastname = details.lastname;
                                     obj.image = details.image;

                                list.push(obj);
                            });
                    }
                });
            });
         });
       console.log(list);
       res.send(list);
};


现在执行此代码。它返回空数组。我该如何解决这个问题?

最佳答案

您正在for循环中调用异步函数。这就是list为空的原因。

您可以使用async解决此问题。

var async = require('async');

function GetConnections_V2(req,res){

    Connection.find({"user_id":"55006c36c30f0edc5400022d"})
     .exec(function(err,connections){

        var list = [];

        async.each(connections, function(connection, callback){
            var obj = new Object();
            obj.friend_id = connection.user_id_friend;

            User.findById(connection.user_id_friend)
                .exec(function(err,user){
                    if(user !== null) {
                        obj.friend_email = user.email;
                        obj.friend_details_id = user.details;
                        UserDetail.findById(user.details).exec(function (err, details) {
                            obj.firstname = details.firstname;
                            obj.lastname = details.lastname;
                            obj.image = details.image;

                            list.push(obj);
                            callback();
                        });
                    } else {
                        callback();
                    }
            });
        }, function(err){
            return res.send(list);
        });
    };
}


希望对您有帮助。

09-26 02:12