title: Javascript - synchronizing after asynchronous calls
body: <p>I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful.  The object is built such that instantiating an instance of it will automatically make these 2 calls.  The 2 calls share a common callback function that operates on the returned data and then calls another method.  The problem is that the next method should not be called until both methods return.  Here is the code as I have implemented it currently:</p>
  
  <pre><code>foo.bar.Object = function() {
  this.currentCallbacks = 0;
  this.expectedCallbacks = 2;
  
  this.function1 = function() {
      // do stuff
      var me = this;
      foo.bar.sendRequest(new RequestObject, function(resp) {
          me.commonCallback(resp);
          });
  };
  
  this.function2 = function() {
      // do stuff
      var me = this;
      foo.bar.sendRequest(new RequestObject, function(resp) {
          me.commonCallback(resp);
          });
  };
  
  this.commonCallback = function(resp) {
      this.currentCallbacks++;
      // do stuff
      if (this.currentCallbacks == this.expectedCallbacks) {
          // call new method
      }
  };
  
  this.function1();
  this.function2();
  }
  </code></pre>
  
  <p>As you can see, I am forcing the object to continue after both calls have returned using a simple counter to validate they have both returned.  This works but seems like a really poor implementation.  I have only worked with Javascript for a few weeks now and am wondering if there is a better method for doing the same thing that I have yet to stumble upon.  </p>
  
  <p>Thanks for any and all help.</p>