0

I have the following function:

/*global chrome*/
export function retrieveJSON() {
    var returnVal;

    chrome.storage.sync.get(['deadlinelist'], res => {
        let result = res.deadlinelist;
        console.log(result, "<- result var");

        returnVal = result;
    });
    console.log(returnVal, "<- returnVal var");

    return returnVal;
}

It uses the chrome.storage api and when I try to run it in my chrome extension, the first console.log outputs my expected json object, but when I try to mutate the value returnVal, it leaves it unchanged, hence the second console.log outputs undefined. I thought variables outside of functions could be mutated, whats the problem?

help needed thanks

feverdreme
  • 467
  • 4
  • 12
  • maybe will help you: https://stackoverflow.com/questions/34754770/how-do-i-call-chrome-storage-sync-get-and-assign-variables-on-page-load – Filipe Jan 02 '21 at 03:24

1 Answers1

0

Your 2nd console statement runs before the callback function has executed (due to javascript's asynchronous nature). As a solution, you could move the 2nd console statement inside the callback function.

export function retrieveJSON() {
    var returnVal;

    chrome.storage.sync.get(['deadlinelist'], res => {
        let result = res.deadlinelist;
        console.log(result, "<- result var");

        returnVal = result;
        
        console.log(returnVal, "<- returnVal var");

        return returnVal;
    });
}
Lahiru Tennakoon
  • 621
  • 1
  • 6
  • 8