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