本文介绍了最佳解决方案等待所有的ajax回调被执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有来自ajax的请求。我想在所有回调被触发时执行一些操作。除了这种方法之外,如何做到这一点:

 (function($){
var sources = //source1.com','http://source2.com'],
guard = 0,
someHandler = function(){
if(guard!= sources.length){ return;}
//做一些动作
};

for(var idx in sources){
$ .getJSON(sources [idx],function {guard ++; someHandler();})
}
})(jQuery)

我不喜欢这里的是,在这种情况下,我不能处理响应失败(例如,我不能设置超时响应来)和总体方法(我想应该有一种方式使用更多的功率)



任何想法?



尊敬!



UPD:感谢您使用链接回调的解决方案。我发现了一个好方法:。这是在注释中提出的:

 (function hidenext(jq){
jq.eq(0)。 fadeOut(fast,function(){
(jq = jq.slice(1))。length&& hidenext(jq);
});
}) ('div#bodyContent a'))

稍微调整一下就可以等待

h2_lin>解决方案

也许你可以级联下载,所以第一个getJSON的回调触发从下一个源下载,等等?然后在最后一个回调中你没有源,可以调用你的'done'函数。


Imagine we have to sources to be requested by ajax. I want to perform some actions when all callbacks are triggered. How this can be done besides this approach:

(function($){
  var sources = ['http://source1.com', 'http://source2.com'],
  guard = 0,
  someHandler = function() {
    if (guard != sources.length) { return; }
    //do some actions
  };

  for (var idx in sources) {
    $.getJSON(sources[idx], function(){ guard++; someHandler(); })
  }
})(jQuery)

What I don't like here is that in this case I can't handle response failing (eg. I can't set timeout for response to come) and overall approach (I suppose there should be a way to use more power of functional programming here)

Any ideas?

Regards!

UPD: Thanks for solution with chaining callbacks. I found a good approach here:. this is what was proposed in comments:

(function hidenext(jq){
    jq.eq(0).fadeOut("fast", function(){
        (jq=jq.slice(1)).length && hidenext(jq);
    });
})($('div#bodyContent a'))

With a little bit of tweaking it can wait for the last callback.

Now I want to handle properly long running requests. Any clues?

解决方案

Maybe you could 'cascade' the downloads, so the callback of the first getJSON triggers download from the next source, and so on? Then in the last callback you have no sources left and can call your 'done' function.

这篇关于最佳解决方案等待所有的ajax回调被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:02