To keep variables in background.js in chrome extension I need to reinitiate some global variables, and I meet some difficulties.
Here is the code(fiddle) that I want to use to illustrate the problem:
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 above code snippet, the temp
variable would sometimes be null and to ensure that temp is not null I should call an async function someTimeConsumingThing
. As we can see, the console.log outputs a Promise rather than 10; and an error would occur if I add await before a():
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules"
How can I tackle this problem? I have read many related but unhelpful answers here and I don't know how to optimize my search input to get the most related question. This problem would be very naive for JS experts and there are certainly available answers on this site.
CodePudding user response:
A function that calls an async function and needs the result of that function, must in itself (by definition) be asynchronous.
Just change b
so that it is an async function:
async function b(){
let localTemp = await a();
console.log(localTemp);
}
CodePudding user response:
You forgot to use await
when calling a()
, which means you printed the returned promise instead of the async result of a()
. The containing function therefore also needs to be async
, since it contains an await
call.
Note that it's good practice to mark the someTimeConsumingThing
function as async, because it returns a Promise.
Also note that your someTimeConsumingThing
function sets temp to 10 immediately, and then delays until returning. I've rewritten it so it only sets temp to 10 after the delay has completed.
let temp = null;
async function someTimeConsumingThing() {
return new Promise(resolve => {
setTimeout(()=>{
temp = 10;
resolve();
}, 2000);
})
}
async function a(){
if(temp==null){
await someTimeConsumingThing();
}
return temp;
}
async function b(){
let localTemp = await a();
console.log(localTemp);
}
b();