在node.js中同步调用

时间:2015-10-19 09:33:09

标签: javascript angularjs node.js mean

我在node.js中创建函数来从mongolab获取数据。返回json只是简单的get方法

这是我的代码:

app.get('/api/get_conversation_all_carer/:carer_id', function(req, res){
    //Sender = user and receiver = carer
    var values = [] ;

    Conversation.aggregate([
            { 
                $match: {
                    receiver_id: req.params.carer_id
                }
            },
            { 
                $group: {
                    _id: "$sender_id",
                }
            }
        ],
        function(err, result) {
            if (err) {
                console.log(err);
                return;
            }

            for(var j = 0; j < result.length; j++) {
                var object = {
                    "sender_id": result[j]._id,
                    "message": "",
                    "datetime": "",
                    "img": "",
                    "name":""
                };

                User.findOne({"_id": result[j]._id}, function(err, docs) {
                    object.img = docs.profile_pic;
                    object.name = docs.first_name;
                });

                Conversation.findOne({
                        $and: [
                            {
                                'receiver_id': req.body.carer_id
                            },
                            {
                                'sender_id': object.sender_id
                            }
                        ]
                    },
                    {},
                    {
                        sort: {
                            'timer' : -1
                        }
                    },
                    function(err, docs) {
                        object.message = docs.message;
                        object.datetime = docs.timer;
                        values.push(object);
                        console.log("======= Inner =======");
                    }
                );
            }
            console.log("====== OUT ======");
            res = values;
        }
    );
});

输出:

====== OUT ======
====== Inner ======

我相信内部字符串应该在Out之前先调用,但是在这里它的反转。我检查过其他文章,但发现难以实施

0 个答案:

没有答案