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.send();
    XHR.onload = next_fn_in_list
  },
  function() {
    XHR.send();
    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;
            xhr.open("GET", 'http://url?param=' + currentValue);
            xhr.send()
        }
    }, function() {});
    chainedAjaxCalls();

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.


Metadata

First published on 2018-05-09

Generated on May 29, 2024, 10:02 PM

Index

Mobile optimized version. Desktop version.