从XMLHttpRequest onload回调中访问全局变量

时间:2014-06-14 01:04:49

标签: javascript xmlhttprequest global-variables closures

globalBuffer回调中设置后,如何访问request.onload变量?我正在学习更多有关闭包的知识,但不明白为什么我无法设置值并在事后检索它。换句话说,为什么console.log(globalBuffer)会返回undefined

var globalBuffer;
var context = new webkitAudioContext();

function loadSound(url) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "arraybuffer";

    request.onload = function() {
        context.decodeAudioData(request.response, function(buffer) {
                // I want to set globalBuffer and retrieve it outside the function
                globalBuffer = buffer;
            }    
        );
    }
    request.send();
}

loadSound("http://upload.wikimedia.org/wikipedia/en/9/9e/Metallica_-_For_Whom_the_Bell_Tolls_%28song%29.ogg");

console.log(globalBuffer);

编辑:

Codepen

1 个答案:

答案 0 :(得分:0)

loadSound是异步方法,console.log是同步的 - 不等到loadSound结束。 globalBuffer声明为值undefined,返回此值而不等待完成loadSound

概念证明如何解决:

function loadSound(url, callback) {
  setTimeout(function() {
    return callback('loaded song from: ' + url)
  }, 1000);
}

loadSound('url to sound clip', function(response) {
  console.log(response);
});

setTimeout用于模拟异步操作 - 如果数据可用 - 回调函数正在调用。