This repository is designed to help you teach JavaScript Promises and Asynchronous programming to students. It uses a "Restaurant Buzzer" analogy to bridge the gap between abstract code and real-world logic.
- The Analogy: The Restaurant Buzzer
- The Three States
- The Syntax Evolution
- The Event Loop (Advanced)
- Classroom Exercises
The Problem (Sync): Standing at the counter waiting for a burger. You can't sit down, and the cashier can't help others. (Blocking).
The Solution (Async):
- You order.
- You get a Buzzer (The Promise).
- You go sit down (Non-blocking).
- When it's ready, the buzzer goes off (Resolved).
- If they are out of meat, it flashes red (Rejected).
Explain that a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.
| State | Description |
|---|---|
| Pending | Initial state, neither fulfilled nor rejected. |
| Fulfilled | The operation completed successfully. |
| Rejected | The operation failed. |
const myPromise = new Promise((resolve, reject) => {
// Some work that takes time...
if (success) resolve(data);
else reject(error);
});Then/Catch (The Blueprint):
getData()
.then((res) => console.log(res))
.catch((err) => console.error(err));Async/Await (The Modern Standard):
async function handleData() {
try {
const res = await getData();
console.log(res);
} catch (err) {
console.error(err);
}
}Teach students that JavaScript handles tasks in order of priority:
- Call Stack: Normal code (runs first).
- Microtasks: Promises (runs second).
- Macrotasks:
setTimeout,setInterval(runs last).
- The ATM: Create a promise that resolves if balance > withdrawal amount, and rejects if not.
- The Traffic Light: Chain three promises (Green -> Yellow -> Red) using
setTimeout. - The Race: Use
Promise.allto see who "wins" between three parallel network requests (simulated).
Run the demo code:
node index.js