0

I fetch data from chrome local storage using this function:

function getStorageByKey(key) {
  chrome.storage.sync.get(key, function(obj) {
    var error = chrome.runtime.lastError;
       if (error) {
           console.error(error);
       }
  console.log('function log')
  console.log(obj)
  return obj
  });
}

I call it like this:

var storage = getStorageByKey('hidden_threads')
console.log("function's return")
console.log(storage)

and the logging output is:

function's return
undefined
function log
{hidden_threads: Array(1)}

I guess this means that the data is being passed through the function appropriately, but I don't understand why console.log(storage) happens before the function finishing execution. I assume that's why it is returning undefined, but not sure about the mechanism that causes this.

metersk
  • 11,803
  • 21
  • 63
  • 100
  • 1
    This is due to asynchronous execution of the callback function. – Vasan Oct 28 '17 at 21:59
  • @metersk your logging output is hard to understand. Which is the output `console.log(storage)`? Also what is "function's return"? Can you show us the actual output? – fraxture Oct 28 '17 at 21:59
  • @fraxture the output of `console.log(storage)` is `undefined`. `function's return` was just a string marker i used to show the order of things happening. i guess as it turns out the function isn't actually returning anything. – metersk Oct 28 '17 at 22:07

0 Answers0