Lab 09: Async TypeScript

Objective

Write type-safe async code: Promise types, async generators, parallel vs sequential execution, timeout/retry patterns, and typed fetch wrappers.

Time

35 minutes

Prerequisites

  • Lab 02 (Functions), Lab 08 (Error Handling)

Tools

  • Docker image: zchencow/innozverse-ts:latest


Lab Instructions

Step 1: Promise Types

// Promise<T> — resolves to T
const p1: Promise<number> = Promise.resolve(42);
const p2: Promise<string> = new Promise(resolve => setTimeout(() => resolve("done"), 100));

// async function always returns Promise<T>
async function fetchNumber(): Promise<number> { return 42; }
async function mayFail(fail: boolean): Promise<string> {
    if (fail) throw new Error("Failed!");
    return "Success";
}

// Awaited<T> — unwrap Promise type
type T1 = Awaited<Promise<string>>;               // string
type T2 = Awaited<Promise<Promise<number>>>;      // number
type T3 = Awaited<ReturnType<typeof fetchNumber>>; // number

(async () => {
    console.log(await fetchNumber());          // 42
    console.log(await mayFail(false));         // Success
    try { await mayFail(true); }
    catch (e) { console.log("Caught:", (e as Error).message); }
})();

💡 Awaited<T> (TypeScript 4.5+) recursively unwraps Promise types. Awaited<Promise<Promise<string>>> = string. This is used by ReturnType when dealing with async functions — Awaited<ReturnType<typeof asyncFn>> gives you the resolved value type.

📸 Verified Output:


Step 2: Parallel vs Sequential Execution

💡 Promise.all vs Promise.allSettled: Promise.all rejects immediately if ANY promise rejects (fail-fast). Promise.allSettled waits for ALL promises and gives you both fulfilled and rejected results. Use allSettled when you need to process all results even if some fail.

📸 Verified Output:


Step 3: Async Generators & Iterators

💡 async function* + for await...of is the TypeScript way to process lazy async sequences — database cursors, API pagination, file streams, WebSocket messages. The generator pauses at each yield until the consumer is ready for the next item, creating natural backpressure.

📸 Verified Output:


Steps 4–8: Timeout, Retry, Queue, AbortController, Capstone

📸 Verified Output:


Summary

TypeScript async programming is fully typed. You've covered Promise<T>, Awaited<T>, parallel/sequential patterns, async generators with pagination, timeout/retry wrappers, an async concurrency queue, AbortController, and a typed async pipeline runner.

Further Reading

Last updated