Loop with each iteration only happening after jQue

2019-02-18 06:38发布

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...

2条回答
We Are One
2楼-- · 2019-02-18 07:04

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/

查看更多
爷的心禁止访问
3楼-- · 2019-02-18 07:16

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).

查看更多
登录 后发表回答