Javascript List Object无法添加JSON? Node.JS,Firebase

时间:2016-09-20 23:53:20

标签: javascript node.js firebase-realtime-database

router.get('/getAllMeals',function(req,res){    

    var allMeals = [];
    allMeals.push("foo");

    mealsRef.on("value",function(dataSnapShot){
        dataSnapShot.forEach(function(child){
            console.log(child.val());
            var oneMeal = child.val();
            allMeals.push(oneMeal);
        });
    }); 

    allMeals.forEach(function(obj){
        console.log(obj);
    });

    res.send(allMeals);
}); //RETRIEVE ALL

在上面的代码中,我不能将oneMeal作为有效的JSON对象添加到我创建的allMeals数组中。 console.log的结果只显示“foo”,长度也是1。

2 个答案:

答案 0 :(得分:3)

假设mealsRef.on("value",function(dataSnapShot){是有效事件;您需要在该回调中调用res.send(allMeals);。基本上你的反应太快了。

答案 1 :(得分:0)

在回调中的datasnapshot.foreach之后移动res.send,async hell就是在打你。