VDog VDog - 2 months ago 19
Javascript Question

How do I return a snapshot.val() from Firebase to a variable?

var getListings = function () {
listingsRef.once("value").then(function(snapshot) {
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};


I have the following method.
console.log(snapshot.val())
is working as expected. However, if I
return snapshot.val()
it returns undefined. I cannot seem to figure out how to do
var currentSnapshot = getListings()

Answer

Return a Promise from get listing. Consume the Promise using resolve and reject functions.

var getListings = function () {
    return listingsRef.once("value");
};

var currentSnapshot;

function loadListing(){
    getListings.then(setListing, showError);
}

function setListing(snapshot){
    currentSnapshot = snapshot.val()
}

function showError(e){
    console.log(e);
}

function init(){
    loadListing();
}