Is there a design pattern for handling concurrent AJAX requests?

I am developing a web application to fetch data from multiple web services (let's say just two for simplicity). What should be retrieved from one service is independent of what was retrieved from the other, so I can run AJAX requests in parallel. Then I need to do some action when both requests returned their data. Since this seems to be something very common, I'm wondering if there is a well-formed and accepted design pattern for this. What I have been doing so far is (using jquery):

var data1 = null;
var data2 = null;

$.ajax({
    url : url1,
    success: function(data) {
        data1 = data;
        if(data2) perform();
    },
});

$.ajax({
    url : url2,
    success: function(data) {
        data2 = data;
        if(data1) perform();
    },
});

function perform() {
    //do interesting stuff on data1 and data2
}

      

Would you like that?

+3


source to share


2 answers


You can do it

Check: jQuery: api.jquery.com/jquery.when

we can use a jQuery method $.when()

that takes a list of these Deferred objects (all jQuery Ajax methods return deferred objects) and then provides a single callback.

Syntax



$.when(

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request)

).then(function() {

  // All have been resolved (or rejected), do your thing

});

      

Example:

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

      

+6


source


When I have multiple ajax requests, I usually like to maintain a list of urls. I am creating a list of promises and applying a function to them $.when

. Something like that:

var urls = [url1, url2];

var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
  endpoints.push($.ajax(urls[i]));
}
$.when.apply($, endpoints).done(function () {
  // Function arguments array differs if we have one or more than one endpoint.
  // When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
  // When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
  // Normalize the single endpoint to the generic list one.
  var args = endpoints.length > 1 ? arguments : [arguments];
});

      



Or more concise:

var urls = ['page1', 'page2'];
$.when.apply($, $.map(urls, $.ajax)).done(function () {
  console.log(arguments);
});

      

+1


source







All Articles