これを使用する以外に選択肢がない場合は、集計を使用できます。
var data; // will contain the retrieved data
/**
* Grab data from the first URL in the list, adding it
* to the global data variable. If the list is empty,
* we got all the data and we succeed. If an XHR fails, we fail.
*/
function prepData(urlList, success, fail) {
if(urlList.length===0) {
succes(); // wrap in timeout if you need to break out of call chain
return;
}
var xhr = new XMLHttpRequest();
var url = urlList.splice(0,1)[0];
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.status === 200 && xhr.readyState === 4) {
data += xhr.responseText;
prepData(urlList, success, fail);
} else {
fail(urlList, xhr); // again, wrap in timeout to break out of call chain
}
}
}
次に、次のようなコードでこれを呼び出すことができます。
/**
* prepare our data prior to application "start"
*/
prepData(['...','...','...'], function (){
console.log("finished aggregating data");
// all went well. Start the actual data-consuming code
}, function(notLoadedList, failedXhrObject){
console.log("ohnoes!", notLoadedList, failedXhrObject);
// something went wrong, and we can fail gracefully
});