Lab 06: Promises & Async/Await

🎯 Objective

Master JavaScript's asynchronous programming model — callbacks, Promises, async/await, and error handling for async code.

📚 Background

JavaScript is single-threaded but non-blocking — I/O operations (network, files, timers) happen asynchronously. Callbacks were the original solution but lead to "callback hell." Promises (ES6) clean this up with chainable .then(). async/await (ES2017) makes async code read like synchronous code. Every modern JS developer must be fluent in all three.

⏱️ Estimated Time

40 minutes

📋 Prerequisites

  • Lab 5: Classes & OOP

🛠️ Tools Used

  • Node.js 20

🔬 Lab Instructions

Step 1: Callbacks (Foundation)

📸 Verified Output:

Step 2: Promises

📸 Verified Output:

Step 3: async/await

📸 Verified Output:

Step 4: Promise.all, Promise.race, Promise.allSettled

📸 Verified Output:

Step 5: Sequential vs Parallel Execution

📸 Verified Output:

Step 6: Async Error Handling Patterns

📸 Verified Output:

Step 7: Async Iteration

📸 Verified Output:

Step 8: Real-World Async Pattern — Retry with Backoff

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Forgetting await: const data = fetchData() — without await, data is a Promise, not the value.

  2. await outside async: await only works inside async functions.

  3. Sequential when parallel is possible: await a(); await b() is slow — use Promise.all([a(), b()]).

  4. Swallowing errors: promise.catch(() => {}) silently ignores errors — always log or rethrow.

  5. Using async in forEach: arr.forEach(async fn) doesn't wait for promises — use for...of or Promise.all.

📝 Summary

  • Callbacks → Promises → async/await: each solves callback hell

  • async function always returns a Promise; await pauses until resolved

  • Promise.all([]) — parallel, fails fast; Promise.allSettled([]) — parallel, all results

  • Promise.race([]) — first settlement wins; Promise.any([]) — first success wins

  • Always wrap async calls in try/catch or use .catch()

  • for await...of loops over async iterables (API pagination, streams)

🔗 Further Reading

Last updated