开发者

multiple asynchronous $.ajax calls followed by function after all have executed

I'm doing 3开发者_运维百科 asynchronous ajax requests.

Afterwards I need a function executed but only if all 3 requests have finished.

How would I accomplish that?

Due to our framework, I'm limited to the latest 1.4 release.

Thanks, Wesley


You need to have all the response handlers call the same scope/function, and keep track of the returned requests there. Only move on if all requests return. Don't forget to handle error cases.


You can achieve it with Reactive Extension for jQuery. Have a look at this question: trigger event after several ajax calls succeeded


The simplest and a very limited way would be just to nest your ajax calls. But that only works if you make those calls at the same time in the same place.

$.ajax({
  url: "test.html",
  success: function(){
    $.ajax({
      url: "test2.html",
      success: function(){
        // n level nesting
      }
    });
  }
});


Expanding on Andrius's answer, I do something similar to his all the time:

function f1(){
  $.ajax({
    url: "test.html",
    success: function(data){
      //do something
      f2();
    }
  });
}

function f2(){
  $.ajax({
    url: "test2.html",
    success: function(data){
      //do something else
      //maybe call f1() if you want to loop again?
    }
  });
}

I chain together many calls this way. Sometimes I put setTimeout(function(){f2()},1000); If I want to have a slight pause between calls.

And my application requires constant polling from the server, so I have my last one in the chain call the first one. So it will loop forever with only one current call outstanding (so I don't hammer the server with requests)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜