简体   繁体   English

无法推入空数组JS

[英]Unable to push into empty Array JS

The findOne query is returning a user from the DB. findOne查询正在从数据库返回用户。 When i console.log(user) it does print out user data. 当我console.log(user)它确实打印出用户数据。 But for some reason isn't pushing into user_contacts. 但是出于某种原因,它并没有加入user_contacts。 Its just returning as an empty array. 它只是作为一个空数组返回。

get_contacts: function (req, res){
                var user_contacts = [];
                for(var i=0;i<req.body.contacts.length;i++){
                    User.findOne({_id: req.body.contacts[i]._User}, function (err, user) {
                        if(user){
                            console.log(user);
                            user_contacts.push(user);
                        }else{
                            console.log("Error");
                        }
                    })  
                }
            console.log(user_contacts);
            res.json(user_contacts);
            }

This should be so simple, but just cannot see what I am doing wrong. 这应该很简单,但是看不到我在做什么错。 Appreciate the help. 感谢帮助。

Since the call is async - your logs and response are executed before everything is finished. 由于调用是异步的-您的日志和响应会在所有操作完成之前执行。 You'll probably also run into some issues with looping that async call - your best bet is to use $in and then return: 您可能还会在循环异步调用时遇到一些问题-最好的选择是使用$in然后返回:

get_contacts: function (req, res){
    var ids = req.body.contacts.map(function(contact) { return contact._User });
    User.find({_id: {$in: ids}}, function(err, users) {
        res.json(users)
    });
}

User.findOne({}) is async , which mean the callback function where you push data into user_contacts array is executed with delay. User.findOne({})是async ,这意味着将延迟将数据推入user_contacts数组的回调函数。 Therefore, the moment you console.log, user_contacts is still empty. 因此,当您console.log时,user_contacts仍然为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM