6

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); 
7
  • given link seems to be the one of the right approaches and should work. did you face any issue with this implementing it? Commented Sep 13, 2022 at 17:14
  • Haven't tried yet as I was not sure it was applicable. I'll try now. Thanks. Commented Sep 13, 2022 at 17:18
  • The await keyword should come immediately after the equals sign, e.g. tmrs=await chrome.storage.local.get("tmrs"); Commented Sep 13, 2022 at 17:22
  • 1
    Chrome forbids top-level await in a service worker intentionally. It can't be circumvented, so you'll have to use an async function. Commented Sep 13, 2022 at 17:25
  • Your updated code is incorrect: you must use the variable inside the function, not outside. Commented Sep 13, 2022 at 17:29

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.