0

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});
            });

        } 
Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37
venkatesh
  • 39
  • 1
  • 5

1 Answers1

1

Your problem probably is the fact that answerDataRef.child(key).once("value", function(snapAnswerData){ is async, therefore you can't expect to have values line after the forEach that you have mentioned.

Maybe you can use Promise in order to return async value.

felixmosh
  • 32,615
  • 9
  • 69
  • 88