..O Deniz's personal pages
/home /about

Chained ajax calls

May 9, 2018

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 [url1, 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;
            xhr.open("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.

Tags: #programming