12

现在我多次遇到使用 Firebase 的同步和异步函数的问题。我的问题通常是我需要在我编写的函数中进行异步 Firebase 调用。举个简单的例子,假设我需要计算和显示一个物体的速度,并且我的 Firebase 存储了距离和时间:

function calcVelocity() {
    var distance, time, velocity;

    firebaseRef.once('value', function(snapshot) {
        distance = snapshot.val().distance;
        time = snapshot.val().time;

        velocity = distance / time;
    });
    return velocity;
}

$("#velocity").html(calcVelocity());

当然,上面的代码是行不通的,因为firebaseRef.once()是异步调用,所以velocity我们到达的时候还没有设置return velocity;。如果我们将其return放在.on()回调函数内部,则根本不会返回任何内容。

一种解决方案是使我的calcVelocity()函数也异步。

另一种解决方案是存储 Firebase 的缓存版本,该版本同步读取但从 Firebase 异步更新。

这些解决方案中的一种是否比另一种更好?有没有更好的解决方案?

4

3 回答 3

9

另一种方法是使用 Promise 策略。jQuery 有一个很棒的

function calcVelocity() {
    var distance, time, velocity, def = $.Deferred();

    firebaseRef.once('value', function(snapshot) {
        distance = snapshot.val().distance;
        time = snapshot.val().time;

        def.resolve( distance / time );
    });
    return def.promise();
}

calcVelocity().then(function(vel) { $("#velocity").html(vel); });

还请记住,如果返回 null ,snapshot.val().distance;则可能会返回错误!snapshot.val()

于 2012-07-24T18:36:44.183 回答
8

您确定了两种可能性:或者使您的函数也异步,或者缓存最新的 Firebase 数据,以便您可以同步访问它。考虑到您正在编写的应用程序的上下文,您使用哪一个只是偏好和方便的问题。

例如,我们注意到“动作游戏”通常由紧密的渲染循环驱动,而不是由 firebase 数据更改事件驱动。因此,缓存最新的 Firebase 数据以在渲染循环中使用是有意义的。例如:

var latestSnapshot = null;
firebaseRef.on('value', function(snap) { latestSnapshot = snap; });

然后您可以在渲染循环(或其他任何地方)中同步使用 latestSnapshot,尽管您需要小心处理它为空,直到第一个 firebase 回调发生。

于 2012-07-24T18:29:43.863 回答
6

与@Kato 提供的答案相同的想法,但使用Firebase 中的内置承诺看起来像这样

function calcVelocity(snapshot) {
    var distance, time, velocity;

    distance = snapshot.val().distance;
    time = snapshot.val().time;

    return distance / time;
}

function getVelocity() {
return firebaseRef.once('value').then(calcVelocity);
}

getVelocity().then(function(vel) { $("#velocity").html(vel); });
于 2016-02-03T00:29:24.320 回答