Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Making multiple asynchronous XMLHTTPRequests in Javascript

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.

However, currently, only the final item's response is being printed. Does anybody know why this is?

Here is my code:

  var responseData = [];
  var numCompletedRequests = 0;

  inputArray.forEach((element) => {

    let newRequest = new XMLHttpRequest();
    newRequest.open("POST", url, true);

    newRequest.onreadystatechange = () => {
      if (newRequest.readyState === 4 && newRequest.status !== 200) {
        // Request failed
        numCompletedRequests++;
        handleFailedRequest(newRequest); // Another function to handle errors

      } else if (newRequest.readyState === 4 && 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);
  });

For example, if my input array had 3 elements, the output array responseData would be 3 elements long, but would contain 3 identical elements: the response of whichever request finished last.

Does anybody know why this is, and how I can fix it?

Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What about use Promise.All ?

const url1 = "url1"
const url2 = "url2"
const url3 = "url3"

const fetchMultiAsync = async () => {
    const responses = await Prmoise.all([fetch(url1),fetch(url2),fetch(url3)])
    return responses
}

fetchMultiAsync() // return [response of req1, req2, req3]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!