Lab 02: Promises & Async/Await

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master asynchronous JavaScript: Promise creation, chaining, combinators (all/race/allSettled/any), and the cleaner async/await syntax with proper error handling.


Step 1: Creating Promises

// Basic Promise
const success = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Data fetched!'), 100);
});

const failure = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error('Network error')), 100);
});

// Promise.resolve / Promise.reject shortcuts
const immediate = Promise.resolve(42);
const failed = Promise.reject(new Error('Instant failure'));

immediate.then(v => console.log('Value:', v)); // Value: 42
failed.catch(e => console.log('Error:', e.message)); // Error: Instant failure

💡 A Promise represents a value that may be available now, in the future, or never.


Step 2: Promise Chaining

💡 .finally() runs regardless of success or failure — perfect for cleanup.


Step 3: Promise.all — Parallel Execution


Step 4: Promise.allSettled, race, any


Step 5: Async/Await Syntax

💡 async/await is syntactic sugar over Promises. Under the hood it's still Promises.


Step 6: Error Handling with Async/Await


Step 7: Sequential vs Parallel Async


Step 8: Capstone — Async Data Pipeline

Run verification:

📸 Verified Output:


Summary

API
Behavior
Use When

Promise.resolve(v)

Wraps value in resolved promise

Creating instant promises

Promise.all(arr)

Resolves when ALL resolve; rejects on first failure

All-or-nothing parallel tasks

Promise.allSettled(arr)

Waits for all, reports each result

Need all results regardless

Promise.race(arr)

First to settle (resolve or reject) wins

Timeouts, fastest service

Promise.any(arr)

First to RESOLVE wins; rejects if all fail

Fallback sources

async/await

Sync-looking async code

Readability, sequential deps

try/catch with await

Catch async errors

Error handling in async code

Last updated