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
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]