2

I am using MSXML2.ServerHTTP in Jscript (ECMAScript 3)to retrieve some data - I send multiple requests (as I can only retrieve 1,000 rows per request). The number of multiple requests varies, as the total varies. Included in the requests is a function to process the data (push it into an array) once the data is received. Code looks similar to the below;

var H = []; x = 0
for (var i = 0; i<L; i +=1000)
  {H.push(new ActiveXObject('MSXML2.ServerXMLHTTP'));}

for (var i = 0; i<L; i +=1000)

  {H[x].open('GET', 'https://someurl.com', true); 
   H[x].setRequestHeader('Content-Type', 'application/json'); 
   H[x].onreadystatechange = 
      function(e)
          {if (H[x].readyState === 4 && H[x].status === 200) 
           {J.push(H[x].responseText);}};  

   H[x].send(); x++}

So what happens is that my loop runs like 5x (as L is 4700 for example), and X increments from 0 to 4 - however, once the data gets retrieved, the function 'e' looks at the then value of x instead of the value when it gets initialized.

So let's say the 2nd data request gets back - it sees that it's done, executes function e, but that function the looks at the current value of x (which would be 5 after 5 loops) and thus do nothing as there is no H[5]...

Is there a way to set the value of x as a constant in that loop?

Thanks!

JasperD
  • 152
  • 1
  • 3
  • 15
  • 1
    (Well asked question!) Classic problem, called the "closures in loops" problem. See the linked question's answers for details and how to deal with it. Most of them are valid ES3. Simplest way is to declare a function for the body of your `for` loop and call it with `H[x]` and any other call-specific information it needs. `function doRequest(xhr) { xhr.open('GET', ... }` and then `for (var i = 0 ; i < L; i += 1000) { doRequest(H[x]); }` That way, the ready state change handler closes over the context of the function call. – T.J. Crowder Apr 12 '19 at 11:13
  • 1
    Thank you - I had actually searched, but obviously wasn't aware this was called closure. It helps a lot - thank you for taking the time to reply and to point me in the right direction. – JasperD Apr 12 '19 at 13:00

0 Answers0