叫我一个菜鸟,但我似乎无法正常工作:
var value = ""; // Tried this
function getKey(key) {
var value = ""; // And this
chrome.storage.local.get(key, function (data) {
var value = data[key];
console.log(value); // This prints the correct value
});
console.log(value); // But this will always print null
}
知道为什么吗?
该chrome.storage.local.get
调用是异步的。该getKey
函数在执行回调之前返回,因此未设置该值。
为了返回值,getKey
您需要像这样重新定义:
function getKey(key, callback) {
chrome.storage.local.get(key, function(data) {
var value = data[key];
callback(value); // This calls the callback with the correct value
});
}
您的呼叫getKey
将如下所示:
getKey("some_key", function(value) {
// do something with value
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句