Reputation: 39
I have a peculiar ajax scenario that I just can't wrap my head around.
This is the sequence of events that I am trying to co-ordinate:
It seems simple enough, but I can't figure out how to express it.
My understanding of chaining deferred objects is that they are all instantiated immediately, and then data flows through them as they are resolved. But how does this work when one of the items is an array, potentially of size zero?
I know I'm going to need $.when().apply(), to watch the array of responses come in.
I think maybe I need a single deferred object that somehow stands in for the array, but I can't figure out how to express this.
Upvotes: 2
Views: 224
Reputation: 337610
Honestly this sounds like a bad pattern to use as you have N+1 requests all being fired. If you have a lot of items in the array and/or lots of users you could end up DDOSing your own server.
Because of this it would be better practice to change point 2 so that all ids are sent in a single request, or even change point 1 to return all the required data from the elements with the given ids.
That being said, you can achieve what you are asking for by saving the promises returned by jQuery's AJAX methods to an array and then applying that to $.when()
, like this:
$.ajax({
url: '/endpoint1',
data: { foo: 'bar' },
success: function(data) {
var requests = [];
for (var i = 0; i < data.ids.length; i++) {
requests.push(
$.ajax({
url: '/endpoint2'
data: { id: data.ids[i] }
})
);
}
$.when.apply($, requests).done(function() {
// do something when all AJAX requests have completed here...
});
}
});
Upvotes: 3