await Error at Top Level Module in Chrome Extension Service_worker

Viewed 50

I have a sequence of code that is at the top level of my script:

await tmrs=chrome.storage.local.get("tmrs");
console.log(tmrs);
await data=chrome.storage.local.get("Auto_Select_051969");
console.log(data);
if (data==null) {
   store_data();
   await data=chrome.storage.local.get("Auto_Select_051969");
}

However I get the error:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

This is in a service_worker script. Is there some kind of restriction? How do I fix this? TIA.

I found this: Getting this error "await is only valid in async functions and the top level bodies of modules" in chrome extension with async await but I'm not sure this applies or if the anonymous function is really the solution.

Updated Code:

(async () => {
   let tmrs=await chrome.storage.local.get("tmrs");
})();
console.log(tmrs);
1 Answers

Wrap all of your service worker code in an async IIFE, including the definition of store_data().

(async () => {
    function store_data() {
        console.log("storing data");
    }
    
    tmrs = await chrome.storage.local.get("tmrs");
    console.log(tmrs);
    data = await chrome.storage.local.get("Auto_Select_051969");
    console.log(data);
    if (data == null) {
        store_data();
        data = await chrome.storage.local.get("Auto_Select_051969");
    }
})();

Explanation:

https://usefulangle.com/post/248/javascript-async-anonymous-function-iife

Immediately-invoked Function Expression (IIFE), is a technique to execute a Javascript function as soon as they are created. It is good way of declaring variables and executing code without polluting the global namespace. These are also called anonymous functions as they have no defined names.

Very often it is required to use the await operator immediately (for example page load). The await can however be used only inside an async function. But instead of defining a new async function and calling it, it is better to use the IIFE pattern to create an async function that will be immediately called.

Related