简体   繁体   中英

JQuery/Ajax: How to combine several ajaxes into one async ajax with response?

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

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 eg $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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM