Unit 6 · JavaScript in the page
await is only valid in async functions
In a plain script, await only works inside a function marked async. Wrap the waiting code in an async function and call it; keep the async keyword, it is what allows await.
The mix-up
What people often think
“You can write await anywhere.”
What the tutor says
In a plain script, await only works inside an async function. Move the display lines into loadDishes, after the await.
How it works
The browser error reads something like “await is only valid in async functions and the top level bodies of modules”. Modules allow top-level await, but an ordinary <script> does not.
Move the lines that use the data inside the async function, after the await.
Side by side
const dishes = await fetchMenu(); // SyntaxError in a plain scriptasync function loadDishes() {
const dishes = await fetchMenu();
show(dishes);
}
loadDishes();Close cousins of this mix-up
The tutor watches for these in the same lesson.
“The async keyword is just decoration.”
await only works inside an async function. Leave async on loadDishes.
Practise it with a tutor watching
Async and fetch
Ask a server for data, wait for it with await, and show it when it arrives.
Free, no account needed.