Joe Moore
Joe Moore

Reputation: 2023

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.

// 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?

Upvotes: 0

Views: 39

Answers (1)

Unmitigated
Unmitigated

Reputation: 89314

Consider using fetch instead, as it works with Promises.

return Promise.all(
    (await getURLArray()).map(url => fetch(url).then(res => res.json()))
);

Upvotes: 1

Related Questions