1

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. with blocked request

In this second image, I removed the request to the URL which was getting block. Now I'm getting a proper output.

without blocked request

crimson589
  • 1,238
  • 1
  • 20
  • 36
  • 1
    That's how $.when works. [It's documented](https://api.jquery.com/jquery.when/): "The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected." – Cully Nov 20 '20 at 05:45
  • 1
    Does this answer your question? [$.Deferred: How to detect when every promise has been executed](https://stackoverflow.com/questions/19177087/deferred-how-to-detect-when-every-promise-has-been-executed) – Cully Nov 20 '20 at 05:49
  • @Cully No, I tried the answer on that question and I'm still not getting my expected output if one the requests is blocked. So is there anyway to determine if a request was blocked by the browser? – crimson589 Nov 20 '20 at 06:30
  • You might want to update your question to include the code you've tried. – Cully Nov 20 '20 at 06:45
  • @Cully thanks for the help. I just ended up using axios, tried to avoid it since my application already had jQuery. – crimson589 Nov 20 '20 at 07:31
  • You know you can use the [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [native Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)? You don't need axios or query to do this. – Cully Nov 20 '20 at 07:34

0 Answers0