Passing browser.storage.local.get to a Global Variable

OK, I am working on an extension, and I have discovered that using localStorage.setItem() and localStorage.getItem() is a bad idea for about a gazillion reasons.

Instead, I should use browser.storage.local.get() and browser.storage.local.get(), for the reasons listed above.

Under the localStorage API, I simply created a global variable using:
activeMenus = JSON.parse(localStorage.getItem('activeMenus'));

However, while I can retrieve a value using browser.storage.local.get(), I cannot find a way to pass it to a global variable, because browser.storage.local.get() is asynchronous, and so the rest of the code executes before it finishes.

Here is my code:

/* Global variables */
var activeMenus;

function initialize () {
 activeMenus = browser.storage.local.get("actTemp",function(activeMenus){
		console.log("inside initialize\n", JSON.stringify(activeMenus,null,2));
		return(activeMenus);
})
}

initialize();
console.log(JSON.stringify(activeMenus,null,2));

and here is the result in the console log:

undefined                                       options.js:12:1
inside initialize                               options.js:6:3
 {
  "actTemp": {
    "enablebbCode": true,
    "enableHTML": true,
    "enableVbulletin": true,
    "enableXHTML": true,
    "enableMarkDown": true,
    "enableCustom": true,
    "enableSymbol": false
  }
}

I get what is going on: the console log (line 12) outside of the function never sees the promise generated inside the function.

So, is there a way to pass this out to a global variable?

You can write globals from a callback/promise chain. However you’d also have to wait for the promise to be finished when you want to read the global. So either you only start doing the things that depend on the global after the promise has resolved, or alternatively make the promise returned by initialize() the global, so you can await it everywhere.