0

So what I am going to do is to send a bunch of requests at once, and wait for the response, something like this:

for(var i=0;i<n;i++){
    x[i]=new XMLHttpRequest();
    x[i].open("GET",url,true);
    x[i].send();
    x[i].onload=function(){
        if(x[i].status==200){
            //do something
        } else {
            //resend request
        }
    };
}

But clearly this doesn't work, since upon onload of x[i] (here i=1,2,...,n-1), the function invoked will always take i=n-1, because the loop indexed by i finishes before any of the x[i] finishes loading.

Thanks in advance!

JAAulde
  • 19,250
  • 5
  • 52
  • 63
user2386986
  • 119
  • 5
  • 3
    why not use `this.status`? – Bogdan Savluk Jun 15 '14 at 23:10
  • @BogdanSavluk Though my additional question would be: how should I resend the request? I mean, since each x[i] opens a different url, I cannot use this.open(//something), because I can't find the corresponding url... – user2386986 Jun 15 '14 at 23:29
  • you can create separate closure with url parameter for each handler: `x[i].onload=(function(url){ return function(){ /* some logic with url */ }}(url));` – Bogdan Savluk Jun 15 '14 at 23:34

0 Answers0