加载远程数据,缓存,并继续在JavaScript [英] Loading remote data, caching, and continuing in javascript

查看:158
本文介绍了加载远程数据,缓存,并继续在JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本用例。我有我的地方远程存储数据拉一个全局变量。如果没有数据,那么我想先加载它,等待它加载,然后继续处理。我真的不希望使用一个同步的过程,如果我没有。

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.

考虑这样的事情,其中​​_companies是一个全局变量...

Consider something like this where _companies is a global variable...

    if (_companies === undefined || _companies.length == 0) {
       loadExternalData();
    }
    // do something with the data in _companies

我觉得我失去了一些东西明显。我知道我可以调用异步=假,但似乎像一个cludge。我也可以把所有的code块的功能,使一个的if..else,然后调用来自loadExternalData()函数,以及在我的else语句,但再这似乎是一个cludge。好像我应该能够包装在回调整个事情,但我不知道该怎么做。

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.

推荐答案

有一个看看下面的code,包括注释。的code具有相同的结构的问题的功能。如果有不清楚的地方,添加注释。

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
}

另请参阅: MDN:使用XMLHtt prequest

See also: MDN: Using XMLHttpRequest

这篇关于加载远程数据,缓存,并继续在JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆