最好的解决办法,以等待所有AJAX回调将被执行 [英] Best solution to wait for all ajax callbacks to be executed

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

问题描述

想象一下,我们不得不来源,由AJAX请求。我想执行某些操作时,所有的回调被触发。这可怎么除了这种方法来实现:

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)

任何想法?

商祺!

UPD:感谢您​​使用链接回调的解决方案。我找到了一个好办法<一href="http://paulirish.com/2008/sequentially-chain-your-callbacks-in-jquery-two-ways/#comment-24910">here:.这是中提出了意见:

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.

现在我想处理好长时间运行的请求。的任何线索?

推荐答案

也许你可以级联的下载,所以第一的getJSON回调触发从下源码下载,等等?然后在最后一个回调你没有来源左,可以打电话给你完成的功能。

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回调将被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆