I have the following parameters:
a = [{param:'a'}, {param:'b'}, {param:'c'}]
I’d like to make a get request for each parameter, like this:
a.map(function(ai){return $.get('myapi/get?ai='+ai.param)})
How do I do something once all the get requests have finished?
I have tried using $.when, like this:
$.when(
a.map(function(ai){return $.get('myapi/get?ai='+ai)})
)
.done(function(results){
results.forEach(function(ri, i){
ri.success(function(result){
a[i].result = result
}
}
do_something_with(a)
}
unfortunately I am clearly misunderstanding this $.when().done() idiom as when I call do_something_with(a) I don’t have the new .result attribute. I’m guessing it’s because when is seeing a single array and so just passes straight into the .done(), as opposed to waiting for each component get to finish.
Any help would be appreciated!
You need:
i.e. using
Function.applyto call$.when()withthis === $and the rest of the arguments being the contents of the arraymyArray, where that array contains the deferred objects returned by each call to$.get.To answer the second question from your comments, you could pass your array of deferred objects through this map function, which returns a new array of deferred objects which will be resolved at completion of each AJAX call, regardless of whether it succeeded or not.
Note that I’m not sure what parameters (if any) will end up being passed to the final
.donefunction in this instance.If that matters, the deferred objects are always called in order, so you can register a
.donehandler for each of the original promises that stores the AJAX results in an array for later use, and a.failhandler that stores anullvalue instead.That will ensure that your final
.whenhandler isn’t invoked until after each of the individual results are available to you.