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

前端 未结 1 1475
温柔的废话
温柔的废话 2020-11-28 16:07

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 a

相关标签:
1条回答
  • 2020-11-28 16:47

    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

    0 讨论(0)
提交回复
热议问题