0
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

In the above code, I cannot add oneMeal which is a valid JSON object to the allMeals array I created. The result of console.log only shows the "foo" and also the length is 1.

1
  • I submitted a fix for your code, you knew there was an extra }); ? Commented Sep 20, 2016 at 23:58

2 Answers 2

3

Assuming mealsRef.on("value",function(dataSnapShot){ is a valid event; your res.send(allMeals); needs to be called in that callback. Basically you are responding too soon.

Sign up to request clarification or add additional context in comments.

3 Comments

A good read for every NodeJS developer, on asynchronous programming: Callback Hell.
A much better development pattern would be to use ES6 promises. Using Promises completely avoids "callback hell." If you are not using ES6 yet, there is a NodeJS polyfill available on NPM. Here is a link to the polyfill. github.com/stefanpenner/es6-promise
Also, here is a link to the MDN site, which explains their implementation of Promises. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

Just move res.send after datasnapshot.foreach inside callback , async hell is beating you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.