如何一个接一个地同步执行功能

   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

最佳答案

使用.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();

关于javascript - 在javascript中同步执行功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37293010/

10-10 22:34