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