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