Chained synchronous AJAX calls

stuff about computer science and programming
Post Reply
User avatar
dendiz
Site Admin
Posts: 114
Joined: Wed Oct 10, 2018 3:48 am

Chained synchronous AJAX calls

Post by dendiz » Wed Oct 10, 2018 10:42 pm

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

Code: Select all

[
  function() {
    XHR.send();
    XHR.onload = next_fn_in_list
  },
  function() {
    XHR.send();
    XHR.onload = next_fn_in_list
  }, ...
]
you actually don't even need this be a list, because the `onload` will reference the next function to call. This is exactly what reduce does for arrays.

Code: Select all

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.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

Code: Select all

[
  function() {
    XHR.send();
    XHR.onload = next_fn_in_list
  },
  function() {
    XHR.send();
    XHR.onload = next_fn_in_list
  }, ...
]
you actually don't even need this be a list, because the `onload` will reference the next function to call. This is exactly what reduce does for arrays.

Code: Select all

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.

Post Reply