m00saca m00saca - 4 months ago 28
Jade Question

Getting Promise Pending with Firebase and Express/Node.js

I've run into some trouble working with Firebase. I'd like to retrieve data from my Firebase database using my Express server and pass that data as an object I can use in my Jade templates. I want to take data from two different endpoints and set that data to be the value of a key in my

firebaseData
object you'll see below. Instead of receiving an object with keys and the values I expect my two values are each
Promise {<pending>}
. I log my
firebaseData
object out in the console to see this and nothing is rendered in the DOM. Am I rendering the page too quickly? Here is the code I am working with:

app.get("/cac", function(req, res){

var firebaseData = {};

function getFirebaseData(endpoint){
return firebase.database().ref(endpoint).once("value", function(snapshot){
return snapshot.val();
});
}

firebaseData.members = getFirebaseData("CAC_Members");

firebaseData.events = getFirebaseData("CAC_Events");

console.log(firebaseData);
res.render("cac", firebaseData);

});


In the console:

{ members: Promise { <pending> },
events: Promise { <pending> } }


I haven't had any experiences with promises but I feel like what I'm doing should be working. Is there a better way to be doing this? I'd appreciate any pointers!

Answer

The Firebase data is loaded asynchronously. Promises are one way of dealing with this and they're a great fit for your need.

Your code needs to wait until all promises are fulfilled, which is very easy with Promise.all():

app.get("/cac", function(req, res){

  var firebaseData = {};

  function getFirebaseData(endpoint){
    return firebase.database().ref(endpoint).once("value", function(snapshot){
          return snapshot.val();
    });
  }

  Promise.all([getFirebaseData("CAC_Members"), getFirebaseData("CAC_Events")).then(function(snapshots) {
    firebaseData.members = snapshots[0];
    firebaseData.events = snapshots[1];
    console.log(firebaseData);
    res.render("cac", firebaseData);
  });
});
Comments