When trying to maintain variables in the background.js of a Chrome extension, I encountered difficulties that require me to reinitialize some global variables.
Here is the code snippet (view fiddle) I am using to demonstrate the issue:
var temp = null;
function someTimeConsumingThing() {
return new Promise(function(resolve,reject) {
setTimeout(resolve, 2000);
temp = 10;
})
}
async function a(){
if(temp==null){
await someTimeConsumingThing();
}
return temp
}
function b(){
let localTemp = a();
console.log(localTemp);
}
b();
In the provided code, the temp
variable may sometimes be null. To ensure it's not null, an async function someTimeConsumingThing
needs to be called. However, the console output results in a Promise instead of 10. Adding await before calling function a() would lead to the error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules"
If you have insights on how to tackle this challenge, please share. Despite scanning various related responses without success, I am hopeful that experienced JavaScript experts might offer solutions here.