0

app.get('/zones/:id/experiences', function(req,res) {
  var zone_key = req.params.id;
  var recent = [];
  var ref = firebase.database().ref('participants/'+zone_key+'/experiences');
  ref.on("value", function(snapshot) {
    var promises = [];
    snapshot.forEach((snap) => {
      promises.push(firebase.database().ref('experiences').child(snap.val()).once("value"));
      Promise.all(promises).then((snapshots) => {
        snapshots.forEach((usersnap) => {
          recent.push(usersnap.val()); //push objects into the "recent" list
        });
      });
    });
  });
  res.render('experiences',{key: zone_key, list: recent}); //render the view and pass the "recent" list to the client
});

In the above code, I query my Firebase DB to get a bunch of objects which I want to put into a list and then pass the list to my client view page. For some reason, I get the objects that I want from my DB but when I do that line "recent.push(usersnap.val())" the console log shows that I am adding the objects to the list but when I console log the "recent" list before the render, it comes up as empty. Is this a variable in/out of scope issue?

1
  • 2
    You can't render until Promise.all has resolved
    – charlietfl
    Commented Nov 4, 2017 at 23:01

1 Answer 1

2

You can't render until Promise.all has resolved and you need to complete the loop before calling Promise.all(). Currently you are trying to process the whole promise array every iteration of the loop

Something like:

ref.on("value", function(snapshot) {
  var promises = [];
  snapshot.forEach((snap) => {
    promises.push(firebase.database().ref('experiences').child(snap.val()).once("value"));    
  });

  Promise.all(promises).then((snapshots) => {
      snapshots.forEach((usersnap) => {
        recent.push(usersnap.val()); //push objects into the "recent" list
      });
      return recent
    })
    .then(recent => res.render('experiences', {key: zone_key,list: recent}))
    .catch(() => res.render( /* error display config*/ ))
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.