仅在jQuery延迟后/何时才可能不进行递归的情况下,每次迭代才发生循环? [英] Loop with each iteration only happening after jQuery deferred when/then possible without recursion?

查看:106
本文介绍了仅在jQuery延迟后/何时才可能不进行递归的情况下,每次迭代才发生循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在循环中调用jQuery延迟函数,但每次迭代都应等待使用延迟when()

I want to call jQuery deferred functions in a loop but each iteration should wait for the previous iteration to complete using the deferred when()

  function (num_of_iterations) {

    var arr = [];

    for (var i = 1; i < num_of_iterations; ++i) {
      arr.push($.getJSON( ... 1 ... ));
      arr.push($.getJSON( ... 2 ... ));
      ...

      $.when.apply($, arr).then(function() {
        // somehow do the next iter. only now that all the asynch getJSON's are done
      });
    }
    return;
  }

当然,由于getJSON是异步的,因此所有迭代中的所有请求实际上都将在调用任何when之前发送.

Now of course since getJSON is asynchronous all the requests in all iterations will actually be sent before any of the whens are invoked.

我意识到我可以通过调用一个将then中的内容包装起来的函数来使用递归来实现.

I realize I can achieve this using recursion by calling a function that wraps what I have here in the then.

但是我想知道是否有一些我想使用的技术来代替递归.我一直担心递归会在将来的某个时候耗尽堆栈.参数num_of_iterations可能很大.

But I'm wondering if there's some technique I'm missing to use instead of recursion. I'm always worried about recursion using up the stack at some point in the future. The parameter num_of_iterations could be potentially quite large.

我可以为此使用pipe()吗?我在处理有关过滤的所有内容时都在寻找它的文档时遇到很多麻烦...

Can I use pipe() for this? I'm having a lot of trouble grokking the documentation for it with all its talk about filtering...

推荐答案

在这种情况下,我认为您可以使用管道链接.看看这个工作的jsfiddle,让我知道这是您想要的或多或少的东西. http://jsfiddle.net/tchaffee/Df3ay/3/

I think you could use pipe chaining in this case. Check out this working jsfiddle and let me know if this is more or less what you are looking for. http://jsfiddle.net/tchaffee/Df3ay/3/

这篇关于仅在jQuery延迟后/何时才可能不进行递归的情况下,每次迭代才发生循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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