从XMLHttpRequest onload回调访问全局变量



如何在request.onload回调中设置globalBuffer变量后访问它?我正在学习更多关于闭包的知识,但不明白为什么我不能设置值并在事后检索它。也就是说,为什么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

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用于模拟异步动作-如果数据可用-回调函数正在调用

相关内容

  • 没有找到相关文章

最新更新