问题
Basic use case. I have a global variable where I store remotely pulled data. If there is no data then I want to load it initially, wait for it load, and then continue processing. I don't really want to use a synchronous process if I don't have to.
Consider something like this where _companies is a global variable...
if (_companies === undefined || _companies.length == 0) {
loadExternalData();
}
// do something with the data in _companies
I feel like I'm missing something obvious. I understand that I can call async = false but that seems like a cludge. I could also put all the code in the block in a function, make an if..else and then call the function from loadExternalData() as well as in my else statement but again that seems like a cludge. It seems like I should be able to wrap that entire thing in a callback but I don't know how to do that.
回答1:
Have a look at the code below, including the comments. The code has the same structure as the functions in your question. If anything is unclear, add a comment.
var companies; //Cache
function loadExternalData(callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){ //Set readystatechange event
if(xhr.readyState == 4 && xhr.status == 200){ //Request finished: 200 OK
callback(xhr.responseText); //Call callback func with data
}
}
xhr.open("get", "http://example.com", true); //True = async
xhr.send(null);
}
function parseData(data){
if(data) {//If data is defined, set companies
_companies = data;
}
if (typeof _companies == "undefined" || _companies.length == 0) {
loadExternalData(parseData); //Pass callback function
return; //No data, return function
}
//When the function reaches this point, _companies exist.
//Normal function behavior
}
See also: MDN: Using XMLHttpRequest
来源:https://stackoverflow.com/questions/7826746/loading-remote-data-caching-and-continuing-in-javascript