这就是我想要做的:
- 从远程服务器脚本请求 JSON 对象
- 等待,直到 JavaScript 获取所有响应数据
- 从响应对象打印一个值
如果值未定义,我正在尝试在 get config 函数中使用 setTimeout 在 1 秒后调用自身,当它不再未定义时,对值执行某些操作。
或者,我似乎可以创建一些循环数秒的方法,但如果有更好的方法来完成我想要做的事情,我想避免这种情况?我当前的代码似乎没有任何延迟地递归,这会破坏我的运行时间
感谢您的任何想法,代码如下:
function runApplication() {
    var initialiser = new Initialiser();
    var config = new Config();
    initialiser.fetchConfigurations(config);
    config.alertValue('setting1');
}
function Initialiser() {
    debug.log("Started");
}
Initialiser.prototype.fetchConfigurations = function(config) {
    var req = new XMLHttpRequest();
    var url = CONFIGURATION_SERVER_URL;
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            var configObject = eval('(' + req.responseText + ')');
            config.setConfig(configObject);
        } else {
            debug.log("Downloading config data...please wait...");
        }
    }
    req.open("GET", url, true);
    req.send(null);
}
function Config() {
    this.config
}
Config.prototype.setConfig = function(configObject) {
    this.config = configObject;
}
Config.prototype.getValue = function(setting) {
    if(this.config === undefined) {
        setTimeout(this.getValue(setting), 1000);   
    } else {
        return this.config[setting];
    }
}
Config.prototype.alertValue = function(setting) {
    if(this.config === undefined) {
        setTimeout(this.alertValue(setting), 1000); 
    } else {
        alert(this.config[setting]);
    }
}