Best way to retrieve Firebase data and return it, or an alternative way

I am using Firebase for some projects and am liking the platform a lot.

I just stumbled upon a thing that I could not do and was wondering if there was any way to achieve it or if there was an alternative way of doing it.

What I am trying to do is to create a function to retrieve the last X number of entries from my Firebase database and returning the data to the calling function.

Something like this:

function getTwoLatestLocations()
{
    var twoLocations;
    myFirebaseRef.limitToLast(2).once('value', function (dataSnapshot) {
        twoLocations = dataSnapshot.val();
    }, function (errorObject) {
        // code to handle read error
        console.log("The read failed: " + errorObject.code);
    });

    return twoLocations;
}

And then calling it like this:

function someCalcutationsWithTheTwoLastLocations()
{
    var twoLastLocations = getTwoLatestLocations();
    // Do some calculations
}

But as you might have guessed the call to the database reference is asynchronous so the returning object will always be undefined.

Is there a way to do this elegantly so I can keep the methods separated?

P.S. Currently all my code is simply inside the call to the database. Ugly.


To separate the code out, you'd pass in a callback:

function getTwoLatestLocations(callback)
{
    var twoLocations;
    myFirebaseRef.limitToLast(2).once('value', function (dataSnapshot) {
        twoLocations = dataSnapshot.val();
        callback(twoLocations);
    }, function (errorObject) {
        // code to handle read error
        console.log("The read failed: " + errorObject.code);
    });

}

And then calling it like this:

function someCalcutationsWithTheTwoLastLocations()
{
    getTwoLatestLocations(function(twoLocations) {
        // Do some calculations
    });
}

The important thing to always remember is that you cannot wait for something that is loaded asynchronously.

This has been covered quite a few times, including in this top answer from the list of related questions: Handling Asynchronous Calls (Firebase) in functions