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.
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();
}
};