Skip to main content

Lesson 7 of 7

Practice & Quiz - Async TypeScript

Consolidate your async TypeScript skills - Promise<T>, async/await, concurrency patterns, typed fetch, and async generators - with a real-world exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical: Resilient Fetch with Retry

Practical: Resilient Fetch with Retry
// Production-ready fetch wrapper with retry logic and typed Result
type Result<T> = { ok: true; data: T } | { ok: false; error: string };

async function fetchWithRetry<T>(
  url: string,
  validate: (raw: unknown) => T,        // e.g. Zod schema parse
  { retries = 3, delayMs = 500 } = {},
): Promise<Result<T>> {
  let attempt = 0;

  while (attempt < retries) {
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);

      const raw: unknown = await res.json();
      return { ok: true, data: validate(raw) }; // validated ✅

    } catch (err) {
      attempt++;
      if (attempt >= retries) {
        return {
          ok: false,
          error: err instanceof Error ? err.message : "Unknown error",
        };
      }
      // Exponential back-off before retry:
      await new Promise(r => setTimeout(r, delayMs * 2 ** (attempt - 1)));
    }
  }

  return { ok: false, error: "Max retries exceeded" };
}

// Usage with Zod validation:
import { z } from "zod";
const TaskSchema = z.object({ id: z.number(), title: z.string() });

const result = await fetchWithRetry(
  "/api/tasks/1",
  (raw) => TaskSchema.parse(raw),  // throws ZodError on bad shape
);

if (result.ok) console.log(result.data.title); // Task - fully typed ✅
else           console.error(result.error);

Module Quiz

Module Quiz
Question 1 of 5

What does `Awaited<Promise<Promise<string>>>` resolve to?

Tip

Tip

Practice Practice Quiz Async TypeScript in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

TypeScript = JavaScript + static types → fewer bugs, better tooling

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Async TypeScript from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Async TypeScript is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done