Last Updated: February 25, 2016
·
7.016K
· jodosha

jQuery AJAX retry

I'm gonna present something interesting here. I have this JS object, that invokes an external endpoint (via JSONP) to fetch some data. Now, it may happen that the host is down, or causes an error, and of course this breaks our application.

For this purposes I created a poor's man mirror of that service and when we get an error from the master, it fallbacks to this other endpoint.

Starting from 1.5+ the jQuery AJAX object (jqAjax) implements the Promise interface, that means you can use error, or success callbacks, directly on that object (as we do on line #8).

The other interesting aspect is the context, this is the jqAjax of the original request, that means it can manipulated, sent back again with the advantage it's already been setup and still bound with the passed callbacks (ie. fn).

Thanks to the fact JS is a dynamic language, we can safely pass that object to the $.ajax function, which is well engineered and it retries the request.

One last note: this is designed to have just one retry, but it's easy to implement a policy with multiple attempts.

Now here the code:

var Service = (function () {
  // private
  var base_uri          = 'http://service.org';
  var fallback_base_uri = 'http://alt-service.org';
  var jsonp             = function ( url ) { return url + '.jsonp?callback=?' };
  var get               = function ( path, fn ) {
    $.getJSON(jsonp(base_uri + path), fn)
      .error(function( e ){
        this.url = jsonp(fallback_uri + path);
        $.ajax(this);
      })
  };

  // public
  return {
    nodes: function( fn ) {
      get('/nodes', fn);
    }
  };
})();                                                                                                                                                                                               

Service.nodes( function( data ) { /* ... */ });