views:

20

answers:

1

I need to generate a result from 2 XMLHttpRequests. How can I make the requests concurrently and wait for them to both finish?

I've though of something like...

resp1="";
req1.onreadystatechange=function(){if(this.readyState=4)resp1==this.responseText;}
req2.onreadystatechangefunction(){if(this.readyState=4) finish(this.responseText);}
function finish(resp2){
if (resp1=="") setTimeOut(finish(resp2),200);
else {
... both are done...
}

I haven't tested it yet but I assume it would work. Is there a better way? My code needs to be as short and fast as possible.

+1  A: 

You don't need a timer for this.

All you need to do is check in each callback whether the other one finished, and, if so, call finish.

For example:

var resp1 = null, resp2 = null;

req1.onreadystatechange = function() {
    if (this.readyState === 4) {
        resp1 = this.responseText;
        if (resp2 !== null) finish();
    }
};
req2.onreadystatechange = function() {
    if (this.readyState === 4) {
        resp2 = this.responseText;
        if (resp1 !== null) finish();
    }
};
SLaks
Thanks, can you confirm there's no possibilities for multithreading disaster (finish called twice)? I'm not sure if js uses multiple threads for this or not.
graw
Javascript does not support multi-threading, so you don't need to worry about it.
SLaks