在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);
编辑:
答案 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
用于模拟异步操作 - 如果数据可用 - 回调函数正在调用。