0

Is it possible to use $.when asynchronously:

init: function() {
   console.log('begin');
   $.when(
      {async: true},
      this.ajax1(),
      this.ajax2(),
      this.ajax3()
   ).done(function() {
      console.log('success');
   }, function () {
       console.log('error');
   });
   console.log('end');
}

each ajax1, ajax2 or ajax3 can be either sync or async

For not it's not working then I expect, I want to see the next order in console output:

begin

end

success (or error)

But actual output is always:

begin

success (or error)

end

eGoLai
  • 360
  • 1
  • 3
  • 16
  • `$.when` is asynchronous when used that way, always, you don't have to set anything. However, you should **never** use synchronous ajax. – adeneo Feb 11 '16 at 20:49
  • can't you call ajax2 when ajax1 is completed. for e.g. $ajax() { ....., complete: function() { ajax2 call} – user3509208 Feb 11 '16 at 20:53
  • It might have something to do with `jQuery` calling the done callbacks immediately if the first parameter is not a deferred. – MinusFour Feb 11 '16 at 20:55
  • One of my ajax inside $.when is synchronous, that's why it doesn't work. – eGoLai Feb 11 '16 at 20:55
  • similar question: [Javascript callback for multiple ajax calls](http://stackoverflow.com/questions/4368946/javascript-callback-for-multiple-ajax-calls) – Yogi Feb 11 '16 at 20:57
  • Above comment should work ^ – prola Feb 11 '16 at 20:58

1 Answers1

0

you should never use synchronous ajax. – adeneo

The problem was that some of my ajaxes were synchronous because their results are depended.

can't you call ajax2 when ajax1 is completed. for e.g. $ajax() { ....., complete: function() { ajax2 call} – user3509208

So I made them asynchronous and made inner ajaxes on completed for those who data are depended:

init: function() {
   console.log('begin');
   $.when(
      {async: true},
      this.ajax1(),
      this.ajax2()
   ).done(function() {
      console.log('success');
   }, function () {
       console.log('error');
   });
   console.log('end');
}


ajax1: function() {
   return $.ajax('url', {
   async: true,
   success: ... ,
   error: ...)
   );
}

ajax2: function() {
   return $.ajax('url', {
   async: true,
   success: ajax3(),
   error: ...)
   );
}

ajax3: function() {
   return $.ajax('url', {
   async: true,
   success: ... ,
   error: ...)
   );
}

And now it's working!

eGoLai
  • 360
  • 1
  • 3
  • 16