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());
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.
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…