检索 Firebase 数据并返回它的最佳方法,或另一种方法 [英] Best way to retrieve Firebase data and return it, or an alternative way

查看:19
本文介绍了检索 Firebase 数据并返回它的最佳方法,或另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些项目中使用 Firebase,并且非常喜欢这个平台.

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.

我想要做的是创建一个函数来从我的 Firebase 数据库中检索最后 X 个条目并将数据返回给调用函数.

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.

像这样:

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

然后像这样调用它:

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

}

然后像这样调用它:

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.

这已经被涵盖了很多次,包括在相关问题列表中的最佳答案中:在函数中处理异步调用 (Firebase)

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

这篇关于检索 Firebase 数据并返回它的最佳方法,或另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆