Loop with each iteration only happening after jQuery deferred when/then possible without recursion?

一个人想着一个人 提交于 2019-12-01 04:53:34

问题


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;
  }

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

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

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.

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


回答1:


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/




回答2:


Function chaining and recursion is a pretty natural thing in asynchronous JavaScript. As seen in the for statement, your loop will run 10 times. That means you will also have a recursion stack of 10, so there is really nothing to worry about the stack size (unless you screw up your return condition and it runs forever).



来源:https://stackoverflow.com/questions/8931563/loop-with-each-iteration-only-happening-after-jquery-deferred-when-then-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!