0

So I'm putting together a conversion extension for Chrome and am having trouble with pulling data from storage. Here's what I have:

var conversionFactor = 1;
        chrome.storage.sync.get("conversion", function(fetched) {
            var tempCon = fetched.conversion;
            if(tempCon.includes('toKG')) {
                conversionFactor = 0.45;
            } 
            else {
                conversionFactor = 2.2;
            }
        });
    alert(conversionFactor);

So this consistently returns 1. Shouldn't this be assigning a new value before the alert? Failing that, what way is there to extract a value out of chrome.storage for use outside the callback function within the chrome.storage.sync.get statement?

octopushugs
  • 147
  • 1
  • 4
  • 13

1 Answers1

1

chrome.storage.sync.get is an asynchronous operation. Move the alert into the call back function and you will see the proper value.

chrome.storage.sync.get("conversion", function(fetched) {
    var tempCon = fetched.conversion,
        conversionFactor;
    if(tempCon.includes('toKG')) {
        conversionFactor = 0.45;
    } 
    else {
        conversionFactor = 2.2;
    }
    console.log(conversionFactor);
});
robbmj
  • 16,085
  • 8
  • 38
  • 63