EDIT
Ok, so I just ended up using axios. It handles everything properly, even a connection timeout error that isn't handled by $.when
.
I was avoiding axios since I already had jQuery in my application.
I'm using $.when
to wait for a dynamic amount of ajax requests. The code works fine if all requests are sent(completed or failed) but I noticed that if one request is blocked (e.g. chrome blocked one request because of CORS policy) then $.when
seems to fail and just runs even if the other requests aren't done yet.
devices.forEach((device) => {
requestArr.push(
$.ajax({
url: `http://${device.ip_address}:3000/s`,
type: "GET",
timeout: 3000,
})
.done((data, textStatus, xhr) => {
aliveDevices.push(device);
})
.fail((data, textStatus, xhr) => {
deadDevices.push(device);
})
);
})
$.when.apply(null, requestArr).always(function () {
console.log("Alive Devices: " + aliveDevices.length);
console.log("Dead Devices: " + deadDevices.length);
});
In my current testing I have 4 requests, 2 requests would run properly, 1 would fail, and 1 would be block by chrome because of CORS policy. As you can see in this image, expected output is suppose to be Alive 2, Dead 2 or at least if the request wasn't sent then Alive 2, Dead 1.
In this second image, I removed the request to the URL which was getting block. Now I'm getting a proper output.