Lesson 4
async and await
Build a practical mental model for async and await and use it in working JavaScript.
By the end, you will be able to…
- Explain async and await in your own words
- Use async and await in a small program
- Recognize and debug a common failure mode
Build the mental model
async/await is syntax sugar over Promises: await pauses the async function until the awaited Promise settles, letting asynchronous code read top-to-bottom like synchronous code. An async function always returns a Promise.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
await removes the visual nesting of chained .then() calls, making multi-step async logic dramatically easier to read and debug.
Real-world example
Nearly all modern API-calling code — fetch, then parse JSON, then use it — is written with await instead of chained .then() calls.
Common mistakes
- Forgetting the async keyword on a function that uses await
- Awaiting inside a loop when the calls could run concurrently with Promise.all instead
- Forgetting a try/catch, so a rejected await throws uncaught
Try it yourself
Challenge
Write an async function loadDouble(n) that awaits a delayed value and returns it doubled.
Knowledge check
What does an async function always return?
Summary
await pauses an async function until a Promise settles, letting async logic read like straight-line synchronous code.