Master asynchronous programming — the key to building real-world apps that talk to servers and handle delays gracefully.
Sync vs Async
Callbacks & Promises
Async/Await
Fetch API
Modules
Quiz
Sync vs Async
Imagine you're at a restaurant. Synchronous is like ordering food and standing frozen at the counter until your food is ready — you can't do anything else. Asynchronous is like ordering and sitting down to chat with friends while the kitchen prepares your meal. When it's ready, they call your name.
JavaScript is single-threaded — it can only do one thing at a time. But it uses an event loop to handle async operations, so it doesn't freeze while waiting for slow tasks like network requests or timers.
See It In Action
Run this code and look at the ORDER of the output — it might surprise you!
JavaScript — Sync vs Async
Key insight: Even setTimeout(fn, 0) doesn't run immediately! It goes to the async queue and waits for all synchronous code to finish first. This is how the JavaScript event loop works.
Common Async Operations
Operation
Why It's Async
Example
Network requests
Server might take seconds to respond
fetch(), XMLHttpRequest
Timers
Deliberately delayed
setTimeout, setInterval
File reading
Disk I/O is slow
fs.readFile (Node.js)
User events
You don't know when user will click
addEventListener
Callbacks & Promises
A callback is like giving a restaurant your phone number — "call me when my food is ready." A Promise is like getting a buzzer — it will either buzz (resolve) when your food is ready, or flash red (reject) if the kitchen ran out of ingredients.
Callbacks — The Old Way
A callback is simply a function you pass to another function, to be called later:
JavaScript — Callbacks
Callback Hell: When you nest callbacks inside callbacks, the code becomes deeply indented and hard to read. This is called "callback hell" or the "pyramid of doom." Promises were invented to fix this!
Promises — The Modern Way
JavaScript — Promises
Promise states: A Promise is always in one of three states: Pending — still waiting (food being cooked) Fulfilled/Resolved — success! (.then runs) Rejected — something went wrong (.catch runs)
Async/Await
async/await is like Promises with a makeover. Instead of chaining .then().then().then(), you write code that LOOKS synchronous but IS asynchronous. It's like reading a recipe step-by-step: "first do this, await the result, then do that."
JavaScript — Async/Await
Rules of async/await
Rule
Explanation
await only works inside async functions
You must mark the function with async
await pauses the function, not the whole program
Other code keeps running while you wait
Use try/catch for error handling
Replaces .catch() from Promises
async functions always return a Promise
Even if you return a plain value
Fetch API
fetch() is like sending a letter to a server and waiting for a reply. You give it a URL (the address), and it returns a Promise that resolves with the server's response. The response contains data — usually in JSON format.
Let's fetch real data from JSONPlaceholder — a free fake API for testing:
JavaScript — Fetch GET Request
POST Request — Sending Data
JavaScript — Fetch POST Request
🎯 Challenge!
In the GET example, change ?_limit=3 to ?_limit=5 to get more users
In the POST example, change the title and body to your own message
Try fetching from https://jsonplaceholder.typicode.com/todos/1 to get a single todo item
Modules
Modules are like toolboxes. Instead of dumping all your tools on the floor, you organize them: one box for hammers, one for screwdrivers. In JavaScript, each file can be a module that exports its tools, and other files import what they need.
Modules help you organize code into separate files. Here's how they work:
JavaScript — Modules (Concept Demo)
Module Syntax Reference
Syntax
What It Does
Example
export
Makes a function/variable available to other files
export function add() {}
export default
One main export per file
export default class App {}
import { x }
Import named exports
import { add } from './math.js'
import X
Import default export
import App from './App.js'
import * as
Import everything
import * as Math from './math.js'
In React projects, every component is usually its own module. You'll see import React from 'react' and export default function App() everywhere. Modules are the foundation of modern JavaScript!
📝 Chapter 5 Quiz
1. What will console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C"); output?
A, B, C
A, C, B
B, A, C
C, A, B
2. What is a Promise?
A function that runs immediately
A way to store data permanently
An object representing a future value (success or failure)
A type of loop
3. Where can you use the await keyword?
Only inside async functions
Anywhere in JavaScript
Only inside .then() blocks
Only inside loops
4. After calling fetch(url), how do you get the JSON data?
response.data
response.body
JSON.parse(response)
await response.json()
5. How do you import a named export called add from math.js?