Chris
Chris

Reputation: 5191

multiple ajax requests in for loop

As the title states I am sending multiple ajax calls in a for loop. One for each entry in an array.

for (var i = 0; i < myArr.length; i++) {

  var request;
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
  } else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
  }
  request.onreadystatechange=function() {
    if (request.readyState === 4 && request.status === 200) {
      outstandingRequests--;
      if (outstandingRequests === 0) { 
        //some processing would happen in here
      } else {
        //be patient as more requests need to return
      }
    }
  }
  request.open("GET","some_ajax_page.php", true);
  outstandingRequests++;
  request.send();
}

When the request is sent outstandingRequests in incremented and decremented when a response is received. If outstandingRequests is 0 then we have returned from all requests.

My understanding is that because I have declared var request; inside the loop body, request will be local to only that iteration of the loop. Similarly var i = 0; in the for loop initialisation will mean that i is local to the for loop. Therefore the function declared at onreadystatechange should be called when each request returns.

This is true however only the last request ever has a readystate of 4 and a status of 200, so outstandingRequests never gets decremented until the last request returns and therefore never makes it back down to 0 for the extra processing. As each request is a separate request, I expect that all requests should get to a readystate of 4 and a status of 200.

I have tried googling and checking on SO for answers before posting but most contain jQuery or are different problems where only one ajax call is sent. In my example I can see all expected calls being made to the server.

Is my understanding wrong? or am I understanding correctly but have overlooked something else.

Thanks in advance.

Upvotes: 0

Views: 960

Answers (1)

Quentin
Quentin

Reputation: 943207

My understanding is that because I have declared var request; inside the loop body, request will be local to only that iteration of the loop.

No. var declares a variable with function level scope.

You need let (limited support) for block level scope.

Move the body of your loop into a function and then call that function from inside the loop.

Upvotes: 2

Related Questions