I have declared an empty array called answerDataArray
and pushed values into the array (values are snapshots from firebase DB). When I can use console.log(answerDataArray)
outside the forEach
loop it showing an empty array but when I do console.log(answerDataArray)
anywhere inside the forEach
loop I get the populated array. Please tell what happening here.
var ideationContestRef = ideationDataRef.child(contestDataRef.key);
ideationContestRef.once("value", function(snapshot){
if(snapshot.child("answers").exists()){
snapshot.child("answers").ref.once("value", function(snapAnswerKey){
var answerKey = Object.keys(snapAnswerKey.val());
var answerDataRef = db.ref("answerData");
var answerDataArray = [];
answerKey.forEach(function(key){
answerDataRef.child(key).once("value", function(snapAnswerData){
answerDataArray.push(snapAnswerData.val());
});
});
console.log(answerDataArray);
// res.render("ideation", {id: contestId, layout: 'styled.handlebars', page: 'ideation', user_logged_in: user_presence, contestData: snapshot.val(), answerDataArray: answerDataArray});
});
}