我需要一些以下要求的帮助。
答案 0 :(得分:0)
如果您别无选择,可以使用聚合:
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
});