在javascript中同步执行函数

时间:2016-05-18 07:32:57

标签: javascript jquery

如何一个接一个地同步执行函数

   function test1(){
      setTimeout(function(){console.log("should print 1st");},1000);

   }
   function test(){
     test1();
     console.log("should print 2nd");
   }
     function aftertest(){
     var dfd = $.Deferred();

         dfd.done(test()).done(tester());
         //dfd.done(test,tester);   

         //$.when(test()).then(tester());

       console.log("should print 4th");
   }
    function tester(){
       console.log("should print 3rd");
    }
    aftertest();

以下是我迄今为止尝试过的BIN

1 个答案:

答案 0 :(得分:3)

使用.then:

function test1(){
      var defer = $.Deferred();
      setTimeout(function(){console.log("should print 1st");defer.resolve();},1000);
     return defer;
   }
   function test(){
     var defer = $.Deferred();
     test1().then(function() {
       console.log("should print 2nd");
       defer.resolve();
     });
     return defer;
   }
     function aftertest(){
     var dfd = $.Deferred();

         test().then(tester).then(function () {
           console.log("should print 4th");    
         });
         //dfd.done(test,tester);   

         //$.when(test()).then(tester());


   }
    function tester(){
       console.log("should print 3rd");
      return $.when();
    }
    aftertest();