1

I am working on a web site, and at some point in my code, I make some AJAX call:
PART(I)

 for (var i = 0; i < arr.length; i++){
        var id = arr[i].id;
        makeXHRRequest(id);
  }

and the makeXHRRequest()function is something like this:

PART(II)

function makeXHRRequest(id){
var jsonArg = ["id", id];
var jsonString = JsonBuilder(jsonArg);
var requestUrl = getUrl();

$.ajax({
      url: requestUrl,
      type: "POST",
      contentType: 'application/json',
      data: jsonString,
      datatype: "json",
      processdata: false,
      success: function (result, status) {
        console.log(result);
        // TODO check if result is valid
        if(result == null || result == ""){
         //...
        }else{
            for(var i = 0; i < parent.arr.length; i++){
                for(var j = 0; j < count; j++){
                   // !!!!! make another ajax call !!!!!!!!
                    makeAnotherXHRRequest(id);
                }
                }
            }
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
          console.log("in get groupUsers fail");
      }
});

}

Note these are nested AJAX calls -> each ajax call made in part(I) above issues a bunch of sub-ajax calls in part(II). So my question is, if the program want to do some task after all data is ready, how could the program knows when all requests made in part(I) and all request made in part(II) finished?

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165
  • http://stackoverflow.com/questions/11755186/tracking-with-java-script-if-ajax-request-is-going-on-in-a-webpage-or-intercept – Ishank Apr 22 '13 at 03:27

1 Answers1

3

Ajax methods in jQuery return Deferred objects, aka promises, which you can listen to if they are done or not. In your case, we can collect them into an array. Then we use $.when to listen to the promises if they are all resolved.

var promises = [];

function makeXHRRequest(id){
  ...
  //we return the ajax promise
  return $.ajax(..
  ...
}

for (var i = 0; i < arr.length; i++){
  ...
  //we store the promise
  promises.push(makeXHRRequest(id));
}


$.when
 .apply(null,promises) //listen to all the promises
 .done(function(){

   /*code here executes when all ajax promises resolves*/

 });
Joseph
  • 117,725
  • 30
  • 181
  • 234