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:

想象一下,我们必须得到ajax请求的来源。我想在触发所有回调时执行一些操作。除了这种方法,如何做到这一点:

(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:

UPD:感谢带有链接回调的解决方案。我在这里找到了一个好方法:这是评论中提出的内容:

(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?

现在我想要正确处理长时间运行的请求。有什么线索吗?

4 个解决方案

#1


0

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.

也许你可以“级联”下载,所以第一个getJSON的回调会触发下一个源的下载,依此类推?然后在最后一个回调中你没有剩下的来源,可以调用你的'完成'功能。

更多相关文章

  1. 跟踪来自特定来源的用户
  2. 【问题解决方案】ImportError: No module named 'pygal'
  3. Python 黏包及黏包解决方案
  4. 无法安装ndg-httpsclient或者我的解决方案错误
  5. Linux无法连接网络解决方案
  6. Media-S 简介(一个开源的DRM解决方案)
  7. AppScan安全问题解决方案
  8. 无法弄清楚mySQL语法错误的来源
  9. PLSQL乱码解决方案

随机推荐

  1. 再谈多态
  2. Java面试题全集(3)
  3. 03 Linux的常用命令
  4. 你可能不知道的15个 Git 命令[每日前端夜
  5. 能用 CSS 能播放声音吗?[每日前端夜话0xF1
  6. Java面试题全集(2)
  7. 15个 Vue.js 高级面试题[每日前端夜话0xF
  8. 英文都不懂.碰都没碰过编程软件!是心理的
  9. Volatitle的作用
  10. Java面试题全集(1)