VDog
VDog

Reputation: 1173

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()

Upvotes: 0

Views: 6819

Answers (3)

sabithpocker
sabithpocker

Reputation: 15566

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();
}

The other solution is the older way of using callbacks. This is not recommended as it can lead to unmanageable code if there are multiple nested async calls. Promises are a solution to the mess created by callbacks.

var currentSnapshot;
function getListings() {
    listingsRef.once("value", setListing, showError);
};

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

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

function init(){
    getListings();
}

Upvotes: 3

Dan Zuzevich
Dan Zuzevich

Reputation: 3831

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

Does this sorcery work at all?

Upvotes: 1

VDog
VDog

Reputation: 1173

nevermind, this for some reason doesn't work either... although it should?

var getListings = function () {
    var currentItems = [];
    listingsRef.on("value", function(snapshot) {
        currentItems.push(snapshot.val());
    })
    , function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    };

    return currentItems;
};

Upvotes: 0

Related Questions