title: Handling Asynchronous Calls (Firebase) in functions
body: <p>Several times now I have run into an issue with synchronous &amp; 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 &amp; display the velocity of an object, and my Firebase stores distance &amp; time:</p>
  
  <pre><code>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></pre>
  
  <p>Of course, the above code will not work because <code>firebaseRef.once()</code> is an asynchronous call, so <code>velocity</code> has not been set yet when we reach <code>return velocity;</code>. If we place the <code>return</code> inside the <code>.on()</code> callback function, then nothing is returned at all.</p>
  
  <p>One solution would be to make my <code>calcVelocity()</code> function asynchronous as well.</p>
  
  <p>Another solution would be to store a cached version of the Firebase that is read synchronously but updated asynchronously from the Firebase.</p>
  
  <p>Is one of these solutions better than the other? And is there a better solution?</p>