Using $ .when () / $. Promise () with functions that have AJAX inside

Having a really hard time with this problem, I know that $.when() can be used this way (with several AJAX statements) to promise you when they are all done.

http://jsfiddle.net/M93MQ/

  $.when( $.ajax({ url: '/echo/html/', success: function(data) { alert('request 1 complete') } }), $.ajax({ url: '/echo/html/', success: function(data) { alert('request 2 complete') } }) ).then( function () { alert('all complete'); }); 

But this only works with raw $.ajax() , anyway, has the same functionality with function calls , which, in turn, have ajax inside them (and other random logic)?

Pseudo-code idea:

  // The functions having the AJAX inside them of course $.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () { alert('all complete'); }); 
+4
source share
1 answer

Of course, the function returns a promise object.

 function ajaxFunctionOne() { return $.ajax(...) } function ajaxFunctionTwo() { var dfd = $.Deferred(); // on some async condition such as dom ready: $(dfd.resolve); return dfd.promise(); } function ajaxFunctionThree() { // two ajax, one that depends on another return $.ajax(...).then(function(){ return $.ajax(...); }); } $.when(ajaxFunctionOne(),ajaxFunctionTwo(),ajaxFunctionThree()).done(function(){ alert("all complete") }); 
+6
source

All Articles