处理异步调用(火力地堡)函数 [英] Handling Asynchronous Calls (Firebase) in functions

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

问题描述

有好几次,现在我遇到了一个问题,同步和放大器;使用火力地堡异步函数。我的问题是经常,我需要让我写一个函数中的异步调用火力地堡。举一个简单的例子,假设我需要计算和放大器;显示对象的运动速度,以及我的火力地堡存储距离&安培;时间:

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

当然,

,上述code将无法工作,因为 firebaseRef.once()是一个异步调用,所以速度还没有确定然而,当我们到达返回速度; 。如果我们把返回。对()的回调函数中,再没有什么是都回来了。

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.

另一种解决方案是将存储在火力地堡的缓存版本的同步读取,但是从火力地堡异步更新。

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?

推荐答案

您钉上了两种可能性:要么让你的函数异步的为好,或者缓存最新的火力地堡数据,因此可以同步访问。你用哪一个是preference和方便只是一个问题,因为你写的应用程序的情况下。

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.

例如,我们已经注意到,动作游戏通常是由紧张渲染循环,而不是通过火力的数据变化事件驱动。所以是有意义的缓存最新火力地堡数据用于渲染循环。例如:

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同步在渲染循环(或任何其他地方),但你必须要小心处理它是零,直到第一个火力点回调发生。

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.

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

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