title: Making multiple asynchronous XMLHTTPRequests in Javascript
body: <p>I have an array of unknown length (anywhere between 1 and 16), and I'd like to send an XMLHTTPRequest for each item in the array asynchronously. Once the final request is complete, I'd like to print data from each response.</p>
  <p>However, currently, only the final item's response is being printed. Does anybody know why this is?</p>
  <p>Here is my code:</p>
  <pre><code>  var responseData = [];
    var numCompletedRequests = 0;
  
    inputArray.forEach((element) =&gt; {
  
      let newRequest = new XMLHttpRequest();
      newRequest.open(&quot;POST&quot;, url, true);
  
      newRequest.onreadystatechange = () =&gt; {
        if (newRequest.readyState === 4 &amp;&amp; newRequest.status !== 200) {
          // Request failed
          numCompletedRequests++;
          handleFailedRequest(newRequest); // Another function to handle errors
  
        } else if (newRequest.readyState === 4 &amp;&amp; newRequest.status === 200) {
          // Request succeeded
          numCompletedRequests++;
          responseData.push(newRequest.response);
        }
  
        if (numCompletedRequests === inputArray.length) {
          // This is the last request to come in. Ready to print
          console.log(responseData);
          return;
        }
  
      newRequest.send(element);
    });
  </code></pre>
  <p>For example, if my input array had 3 elements, the output array <code>responseData</code> would be 3 elements long, but would contain 3 identical elements: the response of whichever request finished last.</p>
  <p>Does anybody know why this is, and how I can fix it?</p>
  <p>Thanks</p>