JavaScript lesson · 18 min

JavaScript async and await

Write asynchronous code in a readable top-to-bottom style with async functions and await.

Code runs locally in your browser

What you will practice

  • Create an async function.
  • Wait for a Promise with await.
  • Use try/catch with asynchronous code.

What this means

`async` marks a function that works with Promises. An async function always returns a Promise, even when it looks like it returns a normal value.

`await` pauses inside an async function until a Promise settles. It makes asynchronous code read more like step-by-step synchronous code.

When awaited work can fail, use try/catch inside the async function so the error path is clear.

If this is your first time seeing this

async/await is a cleaner way to write Promise-based code.

The code still uses Promises underneath, but it reads more like normal step-by-step instructions.

Mini glossary

async
Marks a function that returns a Promise.
await
Waits inside an async function until a Promise settles.
asynchronous
Work that finishes later, while other code may keep running.

Example from everyday life

async/await is like waiting at a service counter. You ask for a document, wait while it is prepared, and then continue with the next step. You are not pretending the document exists before it is ready.

How it works step by step

  1. The code defines `loadStats`, which returns a Promise after a short delay.
  2. `main` is an async function, so it can use `await`.
  3. `const stats = await loadStats()` waits for the Promise and stores the resolved object.
  4. The code returns `main()` so the lesson runner waits for all asynchronous logs.

Where you will use this

  • A page waits for API data before rendering a list.
  • A file tool waits for the browser to read a selected file.
  • A dashboard waits for several stats before calculating a summary.

Before you run the code

async/await does not remove Promises. It gives you a cleaner way to write Promise-based code.

Use it when a task has clear steps: load data, parse it, calculate something, then display the result.

Common beginner mistakes

  • Using `await` outside an async function in places where it is not allowed.
  • Forgetting try/catch around awaited work that can fail.
  • Thinking await freezes the whole website. It pauses only the async function.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingAwaits the stats object
WaitingCalculates progress after awaiting

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change `completed` from `9` to `6` and predict the percentage.
  • Add another console line after the await.
  • Reject the Promise and see the catch message.