Loading remote data, caching, and continuing in ja

2019-06-13 14:56发布

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条回答
家丑人穷心不美
2楼-- · 2019-06-13 15:38

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

查看更多
登录 后发表回答