1
function getBugVal() {
    var bugVal = "";

    chrome.storage.sync.get('bugId', function (obj) {
        console.log(obj.bugId);
        bugVal = obj.bugId;
        console.log(bugVal + "<- val inside get sync");
    });

    console.log(bugVal + "<- val outside get sync");
    return bugVal;
}

If I call getBugVal() the return value keeps indicating an empty string instead of the actual value from the chrome.storage.sync.get. bugVal is not even saving the string value.

console.log(bugVal + "<- val inside get sync");

yields the correct value within the inner function call. Thoughts?

sowbug
  • 4,644
  • 22
  • 29
ninu
  • 890
  • 2
  • 10
  • 26

1 Answers1

2

Yep. That's how async code works. You'll have to use callbacks. Something like this would probably work.

function workWithBugVal(val) {
    // Do stuff
}

function getBugVal(callback) {
    var bugVal = "";

    chrome.storage.sync.get('bugId', function (obj) {
        console.log(obj.bugId);
        bugVal = obj.bugId;
        callback(bugVal);
    });
}

getBugVal(workWithBugVal);
abraham
  • 46,583
  • 10
  • 100
  • 152