Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you ensure an XMLHttpRequest() has received its full response before continuing?

I’m looping XMLHttpRequests and for each response I’m pushing it to an array.

I use async/await to try to ensure that I only return my array of responses once all of the responses are recieved.

For some reason, with no error, this method is not working and I am not getting the full response array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// looping requests in function

const getFetched = async () => {
  return Promise.all(
    await getURLArray().then(async (requestURLArray) => {
      const fetchedData = [];

      await requestURLArray.map((value, index) => {
        const requestUrl = value;
        const Http = new XMLHttpRequest();
        Http.open("GET", requestUrl);
        Http.responseType = "json";
        Http.send();

        Http.onreadystatechange = (e) => {
          if (Http.response === null) return;      
          fetchedData.push(Http.response);
        };       
      });

      return fetchedData;
    })
  );
};

// calling function to make requests

const fetchedData = await getFetched.then((fetched) => {
  // from the above, if I log fetched it has the correct data in it
  // but this is because of the console updating it after the promise
  // so if I log fetched.length it is 0 - meaning it hasnt properly fetched the data yet
})

What can I do to ensure that the Http request is completely finished before returning the array of responses?

>Solution :

You can use the Promise object to wrap the XMLHttpRequest and return the promise that resolves with the response.

const fetchData = (requestUrl) => {
    return new Promise((resolve, reject) => {
        const Http = new XMLHttpRequest();
        Http.open("GET", requestUrl);
        Http.responseType = "json";
        Http.send();

        Http.onreadystatechange = (e) => {
            if (Http.readyState === 4 && Http.status === 200) {
                resolve(Http.response);
            }
        };
    });
};

const getFetched = async () => {
    const requestURLArray = await getURLArray();
    const fetchedData = await Promise.all(requestURLArray.map(fetchData));
    return fetchedData;
};

This way, the function fetchData returns a promise that resolves with the response, and Promise.all will wait for all the promises to resolve before returning the result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading