2016-09-26 48 views
0
router.get('/getChefMeals/:uid', function(req, res, next) { 
    var userid = req.params.uid; 
    var allMealsIds = []; 
    var allMeals = []; 

    console.log("inside the getChefMeals/UID"); 
    console.log("the uid is " + userid); 

    db.ref("chefs/" + userid).child("meals").once("value",function(dataSnapShot){ 
     dataSnapShot.forEach(function(snap){ 
      allMealsIds.push(snap.getKey()); 
     }); 
     allMealsIds.forEach(function(obj){ 
      console.log("obj should be key of meals " + obj); 
      db.ref("meals/" + obj).once("value",function(dataSnapShot){ 
       // console.log("dataSnapShot is " + dataSnapShot); 
       console.log("dataSnapShot key is " + dataSnapShot.getKey()); 
       console.log("value is " + dataSnapShot.val()); 
       allMeals.push({meal: dataSnapShot.val(), key: dataSnapShot.getKey()}); 
      }); 
     }); 
     console.log("Outside allmealsloop length",allMeals.length); 
     res.render("detail_chef.ejs",{chefMeals: allMeals});  
    }); 
}); 

在上面的代碼塊,我試圖res.renderallMeals對象,它是JSON陣列對象直接到ejs文件中detail_chef。但是,在ejs文件中,它是未定義的。快速渲染陣列對象在EJS中未定義;異步版本

console.log表明,由於快速路由器異步性質,console.log("Outside allmealsloop length",allMeals.length);從第二最後一行返回0

的火力地堡DB console.log返回所有數據就好長度和所述allMeals是與陣列正確的長度。

我只是想知道我怎麼能通過這個數組allMealsejs

回答

0

不是一個接一個地吃飯,你應該在一個查詢中獲得所有餐食,例如$概念,並且在獲得所有膳食後發送回覆的回覆。

如果您必須按照與現在一樣的方法進行操作,則可以使用遞歸,也可以在allMeals長度和allMealIds長度相等時將它們發送給ejs。

router.get('/getChefMeals/:uid', function(req, res, next) { 
    var userid = req.params.uid; 
    var allMealsIds = []; 
    var allMeals = []; 

    console.log("inside the getChefMeals/UID"); 
    console.log("the uid is " + userid); 



    db.ref("chefs/" + userid).child("meals").once("value",function(dataSnapShot){ 
     dataSnapShot.forEach(function(snap){ 
      allMealsIds.push(snap.getKey()); 
     }); 
     allMealsIds.forEach(function(obj){ 
      console.log("obj should be key of meals " + obj); 
      db.ref("meals/" + obj).once("value",function(dataSnapShot){ 
       // console.log("dataSnapShot is " + dataSnapShot); 
       console.log("dataSnapShot key is " + dataSnapShot.getKey()); 
       console.log("value is " + dataSnapShot.val()); 
       allMeals.push({meal: dataSnapShot.val(), key: dataSnapShot.getKey()}); 
if(allMeals.length === allMealIds.length){ 
     res.render("detail_chef.ejs",{chefMeals: allMeals});  

} 
      }); 
     }); 
     console.log("Outside allmealsloop length",allMeals.length); 
    }); 
}); 

但我會建議你使用一個查詢來獲得所有膳食。