All topics
Async/Await
Mind-blowing content: concept card, diagrams, tables, charts, code simulation, and challenges.
Async/Await
Write asynchronous code that looks and reads like synchronous code; avoid callback hell and nested Promises.
Mental model
A Promise is like a receipt: you get something now (the receipt) and the actual result comes later.
Real-world analogy
Ordering food: you get a ticket (Promise). When your order is ready they call your number (await resolves).
Where used
async
await
Promise
non-blocking
async/await
Async/await execution flow
flowchart LR A[Call async function] --> B[Returns Promise] B --> C[await pauses] C --> D[Result ready] D --> E[Resume execution]
- Call an async function — it returns a Promise immediately.
- Use await inside async — execution pauses until the Promise resolves.
- Result is assigned — code continues as if it were synchronous.
- Errors can be caught with try/catch.
Async patterns comparison
| Feature | Callbacks | Promises | Async/Await |
|---|---|---|---|
| Readability | Low | Medium | High |
| Error handling | Manual (err param) | .catch() | try/catch |
| Chaining | Nested callbacks | .then() chains | Sequential code |
| Debugging | Hard | Moderate | Easier (stack traces) |
When to use
- Use Async/Await for new code and when you need sequential async steps.
- Use Promises when you need a single async value or .all()/.race().
- Callbacks only for legacy APIs or event handlers.
Relative time: sync vs async (sample)
Interactive code
async function fetchOrder(orderId) {
const res = await fetch(`/api/orders/${orderId}`);
if (!res.ok) throw new Error('Order not found');
return res.json();
}
// Usage:
fetchOrder(42).then(order => console.log(order));
Execution steps
- Line 1: Define async function; it will return a Promise.
- Line 2: await pauses until fetch resolves; then response is in res. orderId = 42
- Line 3: Throw on HTTP error (4xx/5xx).
- Line 4: Return parsed JSON (wrapped in Promise).
Output
// Run in browser or Node to see API result
Promise lifecycle: pending -> fulfilled or rejected. Async/await lets you wait for the result without blocking the main thread.
Animation: flow
+15 XP
Predict the output
What does
console.log show? async function f() { return 1; }
console.log(f());How this connects
graph LR Callbacks --> Promises Promises --> AsyncAwait[Async/Await] AsyncAwait --> ErrorHandling[Error handling] AsyncAwait --> Fetch[Fetch API]
Prerequisites
- Callbacks
- Promises
Leads to
- Error handling
- Fetch API
Used in