Chained ajax calls

Keywords: url list, nop function, programming model, neat trick, onload, urls, javascript, parallel, confusing, implement, transform. Powered by TextRank.

Sometimes you want to make successive calls to multiple urls one after another - not in parallel. With the programming model for javascript using callbacks this can be a bit confusing to implement properly. Here is a neat trick to do it. say you have a list of urls [rl1, url2, url3] if you could transform this list to

  function() {
    XHR.onload = next_fn_in_list
  function() {
    XHR.onload = next_fn_in_list
  }, ...

you actually dont even need this be a list, because the onload will reference the next function to call. This is exactly what reduce does for arrays.

var chainedAjaxCalls = myList.reduceRight(function(previousValue, currentValue) {
        return function() {
            var xhr = new XMLHttpRequest();
            xhr.onload = previousValue;
  "GET", 'http://url?param=' + currentValue);
    }, function() {});

we iterate over the array with the initial NOP function, and return a function that sets the onload to the previous function. We start from the right so the last requests onload is the nop. then n-1 functions onload is n, etc. this will create a chain of ajax calls for the url list. very nice.


First published on 2018-05-09

Generated on May 29, 2024, 10:02 PM


Mobile optimized version. Desktop version.