Chrome storage.get范围问题

奥马尔·阿里(Omar Ali)

叫我一个菜鸟,但我似乎无法正常工作:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章