chrome.storage.sync.get sync with outer level object, but inner object is not sync?

179 Views Asked by At

I am trying to use chrome.storage.sync.get to get back the settings. What I don't understand is that when I call console.log(settings), it returns the correct values. But if I call console.log(settings.speeds), it returns the old values. I think this has something to do with the async nature of chrome.storage.sync.get. Can someone please explain what's going on here? And if there's a solution to this. I tried using callback but it didn't help. I guess one solution is to use just one level but that's not what I want.

Thanks all for the help.

var settings = {
    speeds: {
        speedInput1: 1.0,  // after get, new value should be 11.23
        speedInput2: 2.0   // after get, new value should be 4.50
    },
    shortcuts: {
        shortCut1: '1',
        shortCut2: '2'
    }
};


chrome.storage.sync.get(settings, function(result) {
    // Retrieve speed settings
    for (var key in settings.speeds) {
        if (key in result.speeds) {
            settings.speeds[key] = result.speeds[key];
        }
    };

    // Retrieve shortcut settings
    for (var key in settings.shortcuts) {
        if (key in result.shortcuts) {
            settings.shortcuts[key] = result.shortcuts[key]
        }
    };
});

console.log(settings); // correct updated values
console.log(settings.speeds); // old values
1

There are 1 best solutions below

0
On BEST ANSWER

I found a workaround for anyone who's interested. I wrapped the get call with a function and call that function and that solve the issue. As to why this solves the issue...I have no idea. Below is an example.

function getChromeStorage() {
    chrome.storage.sync.get(settings, function(storage) {
    // get stored values back;
}
getChromeStorage(); // calling it as a function solves the asynchronous issue