0

My checkStorage function gets the correct value based on a key I pass to it. However when I want to return this value and use it in the main code I get 'undefined'

I also get the main alert BEFORE I get the on from within the function... Why is that?

What am I doing wrong here please? Thanks

chrome.storage.sync.set({'myKey': 'myValue'});

function checkStorage(key){
    chrome.storage.sync.get(key, function(result) {
      alert('function: myValue is '+ result[key]) // this works, alerts myValue
      return result[key]
    }); 
  }

alert('main: myValue is ' + checkStorage('myKey')) ; // does not work, alerts undefined
  • Are you aware of *callbacks*? Knowing that concept would tell you what's going on with `chrome.storage.sync.get` and with your first callback function, you can even solve the issue. – Muhammad Talha Akbar Jul 12 '20 at 13:59
  • All of `chrome` API methods that can accept a callback are asynchronous. This is how asynchronous code works. Refer to the linked topics for more info/examples. – wOxxOm Jul 12 '20 at 14:13

0 Answers0