title: Wait to return from a javascript function until condition met
body: <p>This is an odd problem.  I have a client object that I am building up using Crockford-esque public/private members:</p>
  
  <pre><code>var client = function() {
    var that, remote_data, other_data; 
  
    // add public interface
    that.doStuff = function(){...}
  
    // wait for remote resources to load
    remote_data = jsonRequest1();
    other_data  = jsonRequest2();
  
    return that;
  };
  </code></pre>
  
  <p>The problem I'm having is that I need to load some remote JSON resources prior to returning the new 'that' object (which signals a ready client). Data is returned asynchronously (obviously), and I am setting boolean variables to indicate when each remote resource has returned.</p>
  
  <p>I've thought about doing something like the following:</p>
  
  <pre><code>return whenInitialized(function() { return that; });
  </code></pre>
  
  <p>The whenInitialized function returns whether or not both of the boolean flags are true.  I'd use this with a combination of setInterval, but I am sure this won't work.</p>
  
  <p>Would appreciate your suggestions.</p>