Run function after another one completes

前端 未结 3 992
囚心锁ツ
囚心锁ツ 2020-12-05 21:26
function1 = function(){

  something.on(\'transitionend\', function(){
    // now function2 should run
  });

}

function2 = function(){
  alert(\'ok\');
}

function         


        
3条回答
  •  庸人自扰
    2020-12-05 22:30

    Either you take the promise approach, or you take the callback approach.

    With callbacks, you'd pass function2 as a parameter to function1;

    function1 = function(callback){
    
      something.on('transitionend', function(){
          callback();
      });
    
    }
    
    function2 = function(){
      alert('ok');
    }
    
    function1(function2);
    

    ... but then you get nested-hell if you have function3 dependant on function2, and function4 dependant on 3.

    This is why you'd go down the deferred route;

    function1 = function(){
      var def = new jQuery.Deferred();
    
      something.on('transitionend', function(){
          def.resolve(arguments);
      });
    
      return def.promise();
    }
    
    function2 = function(){
      alert('ok');
    }
    
    function1().done(function2);
    

    ... which would allow you to chain successive functions rather than nesting them (providing they all returned promises, of course).

    Combining event handlers and deferreds is a bit messy. So if you went down the route of having multiple event handlers, you'd end up having to do something lame such as;

    function1 = function(){
      var def = new jQuery.Deferred();
      var wait = 4;
    
      function maybeFire() {
          if (--wait) {
              def.resolve();
          }
      }
    
      something.on('transitionend', maybeFire);
      something.on('somethingelse', maybeFire);
      something.on('somethingelse', maybeFire);
      something.on('somethingelse', maybeFire);
    
      return def.promise();
    }
    
    function2 = function(){
      alert('ok');
    }
    
    function1().done(function2);
    

    The real way of combining multiple deferreds is by using $.when(), but unfortunately here you don't have multiple deferreds, and adding them will be as messy as using the maybeFire approach.

提交回复
热议问题