0

i have the following code

var a = ajax1();
var b = ajax2();

$.when(a,b).done(function(){
  var d = function123();
  $.when(d).done(function(){//doSomething});
});

function function123(){
    var c = ajax3();
    return c.promise();
}


return $.when(a,b,c).promise()//???;

How do i wait for everything to finish before returning the function?

edited: I have test the code using the following:

 var e = $.when(a,b)

.done(function(){
     var d = function123();
     d.done(function(){
        console.log('1');
     });
     return d.done(function(){//doSomething});  
   });

   e.done(function(){
      console.log('2');
   });

my return result is '2 1'. however i am expecting a result of '1 2'. may i know why is that so?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
rotatingFan
  • 35
  • 1
  • 6

1 Answers1

0

How do i wait for everything to finish before returning the function?

You dont! You return the promise and when it is resolved (or rejected) you carry on whatever you were doing.

var e = $.when(a,b).done(function(){
  var d = function123();
  return d.done(function(){//doSomething});  
});

Note the addition of return - this will return your promise. By setting the response of d.done to another variable (e in this case) you have a promise that will be resolved when everything inside is resolved.

e.done(function(){
   //everything is done
});

Also read this Q/A in its entirety: How do I return the response from an asynchronous call?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • @rotatingFan Its hard to read code in a comment. If you have an update to your question (with new code) please click the edit button under your question and put it in. – Jamiec Sep 04 '17 at 08:27