作者:古台山_683 | 来源:互联网 | 2023-05-17 21:53
SeveraltimesnowIhaverunintoanissuewithsynchronous&asynchronousfunctionsusingFireb
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:
现在我已经多次遇到使用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());
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.
当然,上面的代码不会起作用,因为firebaseRef.once()是一个异步调用,所以当我们到达返回速度时,速度还没有设置。如果我们将return放在.on()回调函数中,则不会返回任何内容。
One solution would be to make my calcVelocity()
function asynchronous as well.
一个解决方案是使我的calcVelocity()函数也是异步的。
Another solution would be to store a cached version of the Firebase that is read synchronously but updated asynchronously from the Firebase.
另一种解决方案是存储一个缓存版本的Firebase,该版本可以同步读取,但可以从Firebase异步更新。
Is one of these solutions better than the other? And is there a better solution?
其中一个解决方案比另一个更好吗?有更好的解决方案吗?
3 个解决方案