VCF

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

The mix-upJavaScript
const dishes = await fetchMenu();  // SyntaxError in a plain script
await outside a function.
What worksJavaScript
async function loadDishes() {
  const dishes = await fetchMenu();
  show(dishes);
}
loadDishes();
Inside an async function.

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.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.