我坚持这个异步功能问题。我需要设置一个全局变量,其中包含我从回调函数获得的数据。我怎么能这样做?
var soundId;
soundcheck(soundId, function (num){getSound(soundId, num)});
//callback
function getSound (soundId, result) {
var res = result;
if (!soundId) {
soundId = res;
}
console.log(soundId);
};
function soundcheck(soundId, callback) {
var lpid = $("a#entered_user_link").attr('href').substring(6);
chrome.extension.sendMessage({lpid: lpid}, function(response) {
if (response.resp) {
check = response.resp;
callback(check);
}
});
};
// i need to put response in this variable to use it in future
console.log(soundId);
答案 0 :(得分:3)
您可能希望保持简单,特别是不要遮蔽您的变量。
var soundId;
soundCheck(function(result) {
if(result) {
soundId = result;
};
});
var soundCheck = function(callback) {
var lpid = $("a#entered_user_link").attr('href').substring(6);
chrome.extension.sendMessage({lpid: lpid}, function(response) {
callback(response.resp);
});
};
毕竟没有理由传递soundId
。