//very very usefull plugin for detect when all of nested ajax request is finished.
//same of jquery ajax,only added new arg named "finished".

(function( $ ) {
  $.fajax = function(args) {
    var _success = args.success || function(){};
    var _finished = args.finished || function(){};
    var done = $.fajax.done;
    var started = $.fajax.started;
    args.finished = function(){
      _finished();
      if(done == 0 && started == 0){
        $.fajax.started = 0;
        $.fajax.done = 0;
        $.fajax.laps = [];
      }
    }
    args.success = function(jqXHR, textStatus){
      _success(jqXHR, textStatus);
      $.fajax.done++;
      if($.fajax.done >= $.fajax.started){
        for(i=($.fajax.laps.length-1);i>=0;i--){
          $.fajax.laps[i]();
        }
      }
    }
    $.fajax.laps.push(args.finished);
    $.fajax.started++;
    return $.ajax(args);
  };
  $.extend($.fajax, {
    started: 0,
    done: 0,
    laps: [],
  });
})( jQuery );


//Example

$.fajax({
  url: 'api/fajax.json',
  dataType: 'json',
  success: function(data1){
    console.log('1 success 1');
    $.fajax({
      url: 'api/fajax.json',
      dataType: 'json',
      success: function(data2){
        console.log('2 success');
      },
    });
    console.log('1 success 2');
  },finished:function(){
    console.log('1 finished');
  }
});

//Output
1 success 1
1 success 2
2 success
1 finished