javascript - Getting Promise Pending with Firebase and Express/Node.js -
i've run trouble working firebase. i'd retrieve data firebase database using express server , pass data object can use in jade templates. want take data 2 different endpoints , set data value of key in firebasedata
object you'll see below. instead of receiving object keys , values expect 2 values each promise {<pending>}
. log firebasedata
object out in console see , nothing rendered in dom. rendering page quickly? here code 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 console:
{ members: promise { <pending> }, events: promise { <pending> } }
i haven't had experiences promises feel i'm doing should working. there better way doing this? i'd appreciate pointers!
the firebase data loaded asynchronously. promises 1 way of dealing , they're great fit need.
your code needs wait until promises fulfilled, easy 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
Post a Comment