HTML5, CSS3, jQuery, JSON, Responsive Design...

Parallel Ajax calls

Michael Brown   October 10 2015 01:23:17 AM
Some time ago (4+ years, yikes!) I wrote a post called Getting around Domino‚Äôs Ajax lookup restrictions.  In that post I outlined a way of breaking up a big Ajax call into a number of smaller ones, using recursion.

While this approach works, it does have a serious drawback: it's slow.  That's because with my recursion method, the Ajax calls had to run in sequence.  The second Ajax call was triggered by the .success() callback for first Ajax call.  Then the third Ajax call would be triggered by the .success() callback for the second Ajax call.  And so on.

It turns out that there's a much neater way of achieving this in jQuery, by using promises.  Here's the code:

 $.when(
  $.getJSON(dataPath1),
  $.getJSON(dataPath2),
  $.getJSON(dataPath3)
).then(function(data1, data2, data3) {
  console.log("data1 = " + JSON.stringify(data1[0]));
  console.log("data2 = " + JSON.stringify(data2[0]));
  console.log("data3 = " + JSON.stringify(data3[0]));
});


I've lined up three Ajax calls inside my $.when() call.  The chained .then() call is triggered when, and only when all three Ajax calls have completed and returned their data.  The returned data from each Ajax call is then passed into .then(function()) as variables in sequence; three Ajax calls so three data objects returned.  Nice and simple.

NB: the data objects returned the my function inside the .then() are actually arrays, of which the first member is the JSON data in which I'm interested.  Hence "data1[0]", "data2[0]" etc when I reference them.  (FYI, the second array member is the return status, and the third is the native XHR object.)
Comments

1cghgjh  03/20/2017 12:14:25 AM  zdfgvzxdfgvvd

Welcome to USPS Tracking Track USPS Couriers & Parcels By Entering the USPS Tracking Number Track USPS Courier Online

Enter Your Package Number :- https://www.uspstracking.info/usps-international-mail-tracking/

About