0

How to execute functions synchronously one after the another

 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();

Here is BIN of what I have tried so far.

asked May 18, 2016 at 7:32
2
  • remove setTimeout and change it to function test1(){ console.log("should print 1st"); } Commented May 18, 2016 at 7:45
  • 1
    please explain better what you need. You mix synchronous and asynchronous here. Either you want one or the other, Commented May 18, 2016 at 7:50

1 Answer 1

3

Use .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();
answered May 18, 2016 at 7:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.