在函数中处理异步调用 (Firebase) [英] Handling Asynchronous Calls (Firebase) in functions

查看:31
本文介绍了在函数中处理异步调用 (Firebase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我遇到了好几次同步 & 的问题.使用 Firebase 的异步函数.我的问题通常是我需要在我编写的函数中进行异步 Firebase 调用.作为一个简单的例子,假设我需要计算 &显示对象的速度,我的 Firebase 存储距离和时间:

Several times now I have run into an issue with synchronous & asynchronous functions using Firebase. My problem is often that I need to make an asynchronous Firebase call within a function that I wrote. As a simple example, suppose I need to calculate & display the velocity of an object, and my Firebase stores distance & time:

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 放在 .on() 回调函数中,那么什么都不会返回.

Of course, the above code will not work because firebaseRef.once() is an asynchronous call, so velocity has not been set yet when we reach return velocity;. If we place the return inside the .on() callback function, then nothing is returned at all.

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

One solution would be to make my calcVelocity() function asynchronous as well.

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

Another solution would be to store a cached version of the Firebase that is read synchronously but updated asynchronously from the Firebase.

这些解决方案中的一个是否比另一个更好?还有更好的解决方案吗?

Is one of these solutions better than the other? And is there a better solution?

推荐答案

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

You nailed the two possibilities: Either make your function asynchronous as well, or cache the latest Firebase data so you can access it synchronously. Which one you use is just a matter of preference and convenience, given the context of the app you're writing.

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

For instance, we've noticed that "action games" are usually driven by a tight render loop instead of by firebase data change events. So it makes sense to cache the latest Firebase data for use in your render loop. For example:

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

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

And then you can use latestSnapshot synchronously in your render loop (or wherever else), though you need to be careful to deal with it being null until the first firebase callback happens.

这篇关于在函数中处理异步调用 (Firebase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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