Wait to return from a javascript function until condition met

前端 未结 2 1260
后悔当初
后悔当初 2021-02-14 13:41

This is an odd problem. I have a client object that I am building up using Crockford-esque public/private members:

var client = function() {
  var that, remote_         


        
2条回答
  •  时光说笑
    2021-02-14 14:14

    In order to run code after an asynchronous operation has succeeded, you need a continuation. It can be just a callback that your code calls when the operations are complete.

    Something like this:

    var client = function(done) { // done is the callback
      var that, remote_data, other_data; 
    
      // add public interface
      that.doStuff = function(){...}
    
      // wait for remote resources to load
      var done1 = false, done2 = false;
      var complete1 = function() { done1 = true; if (done2) done(); };
      var complete2 = function() { done2 = true; if (done1) done(); };
      remote_data = jsonRequest1(complete1);
      other_data  = jsonRequest2(complete2);
    
      return that;
    };
    

    But these controlling flags are really annoying and don't really scale. A better, declarative way of doing this is using something like jQuery deferreds:

    $.when(jsonRequest1(), jsonRequest2()).then(done);
    

提交回复
热议问题