Campground
Campground

Reputation: 39

An array of ajax requests from a single request

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:

  1. A single request returns an array of id numbers.
  2. For each id, a new request is sent.
  3. When all those requests have returned, their data is collected and rendered.

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

Answers (1)

Rory McCrossan
Rory McCrossan

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

Related Questions