Callback returns undefined with chrome.storage.sync.get

后端 未结 3 666
滥情空心
滥情空心 2020-12-06 06:14

I\'m building a Chrome extension and I wrote this code.

var Options = function(){};

Options.prototype = {

    getMode: function(){
               return ch         


        
3条回答
  •  醉酒成梦
    2020-12-06 07:12

    Chrome storage API is asynchronous and it uses callback, that's why you're getting this behavior.

    You can use Promise API to overcome this asynchronous issue, which is simpler and cleaner. Here is an example:

    async function getLocalStorageValue(key) {
        return new Promise((resolve, reject) => {
            try {
                chrome.storage.sync.get(key, function (value) {
                    resolve(value);
                })
            }
            catch (ex) {
                reject(ex);
            }
        });
    }
    
    const result = await getLocalStorageValue("my-key");
    

提交回复
热议问题