Chrome 扩展 - Chrome.storage - 为什么 chrome.storage.sync.get returns 未定义?

Chrome Extension - Chrome.storage - Why does chrome.storage.sync.get returns undefined?

出于某种原因,我的 getStorageKeyValue 方法 returns 未定义,而不是之前设置的值。 我为此苦苦思索了大约 3 天。 google 搜索没有解决我的问题,求求您的帮助!如何解决这个问题?

这是我当前的 JavaScript 代码:

// Sets a key and stores its value into the storage
function setStorageKey(key, value){
    chrome.storage.sync.set({ key: value });
}

// Gets a key value from the storage
function getStorageKeyValue(key){
    chrome.storage.sync.get([key], function(result) {
        return result.key;
    });
}

// Set a new key inside the storage
let value = 10;
setStorageKey("K1", value);

// Get the value of the key passed in parameter from the storage
let receivedValue = getStorageKeyValue("K1");

alert("Set value: "+value+" --- Received value: "+receivedValue);
// Results in: Set value: 10 --- Received Value: undefined

找到的解决方案:

// Sets a key and stores its value into the storage
function setStorageKey(key, value){
    chrome.storage.sync.set({ [key]: value });
}

// Gets a key value from the storage
function getStorageKeyValue(key, onGetStorageKeyValue){
    chrome.storage.sync.get([key], function(result) {
       onGetStorageKeyValue(result[key]);
    });
}

// Running our code to see the result:
// 1) Set value & Save it to storage
let value = 10;
setStorageKey("K1", value);

//) 2) Get saved value from storage and display a warning message with the value
getStorageKeyValue("K1", function(key) {
  alert("Set value: "+value+" --- Received value: "+ key);
});
// Results in: Set value: 10 --- Received Value: 10

非常感谢您的回复和帮助。 我希望这个问题对其他开发者有用。

特别鸣谢: 约翰乔平和安德烈亚斯。他们的回复帮助我解决了问题。

chrome.storage.sync.get 是一个异步方法,这就是为什么你需要在它完成获取存储后给它一个回调。所以你不能为此采用过程代码结构。一种解决方案是使用回调结构:

function setStorageKey(key, value){
    chrome.storage.sync.set({ key: value });
}

function getStorageKeyValue(key, onGetStorageKeyValue){
    chrome.storage.sync.get([key], function(result) {
       onGetStorageKeyValue(result.key);
    });
}

let value = 10;
setStorageKey("K1", value);

getStorageKeyValue("K1", function(key) {
  alert("Set value: "+value+" --- Received value: "+ key);
});