node.js 中的值未推入数组

Values not push in array in node.js

我正在 node.js 和 mongodb 合作。我创建了一个数组并尝试推送我的所有值,但它不起作用。见下面的代码。

我的路线:

router.get('/loadLastdata/:rid', loadLastdata);

我的函数:

var loadLastdata = function(req, res)
{
        arrayDefine = new Array();
        History.find( {rid:req.params.rid} , 
        function(err, historyres) 
        {

            if(historyres)
            {
                for (var key in historyres) 
                {
                     console.log('########### In Loop ###############');
                     console.log(historyres[key].data); 
                     arrayDefine.push(historyres[key].data);
                     console.log('########### In Loop ###############');

                    }
                }
            }
        }).limit(1).sort({$natural:-1});
        console.log('########### Array Value ###############'); 
        console.log(arrayDefine);
        console.log('########### Array Value ###############');
    }

在终端控制台中:

########### Array Value ###############
[]
########### Array Value ###############

############ In Loop ##############
[ { __v: 0,
    _id: 57a5d4afaa21a18c247728c5,
    rid_id: '57a2029e0678a6234070e415',} ]
############ In Loop ##############

############ In Loop ##############
[ { __v: 0,
    _id: 57a5e15c86b0c2c528063b27,
    rid: '57a20d56d2472b9043052d39',
 } ]

############ In Loop ##############

由于 for 循环是在回调中定义的,因此它将 运行 异步进行。所以在for循环之后添加日志

  var loadLastdata = function(req, res)
  {
    arrayDefine = new Array();
    History.find( {rid:req.params.rid} , 
    function(err, historyres) 
    {

        if(historyres)
        {
            for (var key in historyres) 
            {
                 console.log('########### In Loop ###############');
                 console.log(historyres[key].data); 
                 arrayDefine.push(historyres[key].data);
                 console.log('########### In Loop ###############');

                }
            }
            console.log('########### Array Value ###############'); 
            console.log(arrayDefine);
            console.log('########### Array Value ###############');
        }
    }).limit(1).sort({$natural:-1});

}