0

I want to redirect to the fastest URL after ajax called all the URLs, but when I alert the value, I get undefined:

var servers = ["url1", "url2", "url3"];
for (var i = 0; i < servers.length; i++) {
  $.ajax({
    type: "GET",
    url: servers[i],
    data: {},
    cache: false,
    success: function(output) { 
      // window.location.href = servers[i]
      alert(servers[i]);
    }
  });
}
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
Choy
  • 452
  • 1
  • 5
  • 19
  • 2
    Try `let i` instead of `var i` (the reason this fails is that `i` is increased a final time thanks to the `i++` right before the loop ends, is now `3` and `servers[3]` is `undefined`) –  May 29 '20 at 11:25
  • @ChrisG i tested, it works, please post your answer – Choy May 29 '20 at 11:28
  • Actually, [this](https://stackoverflow.com/a/30900289/11908502) is the more exact answer in this case. – SMAKSS May 29 '20 at 11:34

1 Answers1

0

You can use Promise.race instead of iteration. MDN

const servers = ["url1", "url2", "url3"];
const requests = servers.map(server => $.ajax({...}));

Promise.race(requests)
    .then(/* handle the fastest request */)
    .catch(/* catch error here */)
vadimk7
  • 6,559
  • 1
  • 12
  • 15