Updated Nov 29, 2026

08 - Async Patterns

📋 Jump to Takeaways

🎁 In Go you block on I/O and the runtime parks the goroutine. In Node you await I/O and the event loop handles the rest. Same result, completely different model — and the difference matters when things go wrong.

Single-threaded. No goroutines, no threads, no parallel execution within a single process. Everything async runs on an event loop. Promises are the core primitive, and async/await is the syntax you'll actually use.

Promises

A Promise is a value that doesn't exist yet. It's either pending, fulfilled, or rejected.

const promise = new Promise<string>((resolve, reject) => {
  setTimeout(() => {
    resolve("done");
  }, 100);
});

promise
  .then((value) => console.log(value))   // "done"
  .catch((err) => console.error(err))
  .finally(() => console.log("cleanup")); // "cleanup"

You'll rarely construct Promises directly. Most APIs return them. But you need to understand the shape.

async/await

async/await is syntactic sugar over Promises. An async function always returns a Promise. await unwraps it.

async function fetchUser(id: string): Promise<{ name: string }> {
  const response = await fetch(`https://api.example.com/users/${id}`);
  const data = await response.json();
  return data as { name: string };
}

// What the compiler sees (roughly):
// function fetchUser(id: string): Promise<{ name: string }> {
//   return fetch(`https://api.example.com/users/${id}`)
//     .then(response => response.json())
//     .then(data => data as { name: string });
// }

Same behavior, much easier to read. Use async/await everywhere.

Error Handling

try/catch works with await. The catch block gets the rejection reason.

async function getUser(id: string): Promise<string> {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    const user = await response.json();
    return user.name;
  } catch (err) {
    // err is unknown in TypeScript 4.4+
    if (err instanceof Error) {
      console.error(`Failed: ${err.message}`);
    }
    throw err; // re-throw if you can't handle it
  }
}

One gotcha: unhandled Promise rejections crash Node.js (v15+). Always handle errors or let them propagate to a top-level handler.

// Global safety net
process.on("unhandledRejection", (reason) => {
  console.error("Unhandled rejection:", reason);
  process.exit(1);
});

Promise.all: Parallel Execution, Fail Fast

Promise.all runs multiple async operations in parallel. If any one fails, the whole thing fails immediately.

async function loadDashboard(userId: string) {
  const [user, posts, notifications] = await Promise.all([
    fetchUser(userId),
    fetchPosts(userId),
    fetchNotifications(userId),
  ]);

  return { user, posts, notifications };
}
// All three requests fire at the same time
// Total time = max(individual times), not sum

Compare to Go's errgroup:

// Go equivalent
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { user, err = fetchUser(ctx, id); return err })
g.Go(func() error { posts, err = fetchPosts(ctx, id); return err })
if err := g.Wait(); err != nil { return err }

Same pattern. Promise.all is just cleaner syntax.

Promise.allSettled: Get All Results

Promise.allSettled waits for everything to finish, even if some fail. Unlike Promise.all, it doesn't short-circuit.

async function checkServices() {
  const results = await Promise.allSettled([
    fetch("https://api.example.com/health"),
    fetch("https://db.example.com/health"),
    fetch("https://cache.example.com/health"),
  ]);

  for (const result of results) {
    if (result.status === "fulfilled") {
      console.log(`OK: ${result.value.status}`);
    } else {
      console.log(`FAIL: ${result.reason}`);
    }
  }
}
// Every result is either { status: "fulfilled", value: T }
// or { status: "rejected", reason: any }

Use Promise.all when you need all results to succeed. Use Promise.allSettled when partial failure is fine.

Promise.race and Promise.any

Promise.race resolves or rejects with the first Promise to settle.

async function fetchWithTimeout<T>(
  promise: Promise<T>,
  ms: number
): Promise<T> {
  let timer: ReturnType<typeof setTimeout>;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error("Timeout")), ms);
  });

  try {
    return await Promise.race([promise, timeout]);
  } finally {
    clearTimeout(timer!); // ! because the Promise executor runs synchronously, so timer is always assigned
  }
}

const data = await fetchWithTimeout(fetch("/api/data"), 5000);
// Either gets the response or throws "Timeout" after 5s

Promise.any resolves with the first Promise to fulfill. It only rejects if all Promises reject.

async function fetchFromFastestMirror(url: string) {
  return Promise.any([
    fetch(`https://mirror1.example.com${url}`),
    fetch(`https://mirror2.example.com${url}`),
    fetch(`https://mirror3.example.com${url}`),
  ]);
}
// Returns the first successful response
// Only throws AggregateError if ALL mirrors fail

AbortController: Cancellation

AbortController is the closest thing to Go's context.Context. It lets you cancel async operations.

async function fetchWithCancel(url: string, timeoutMs: number) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, { signal: controller.signal });
    return await response.json();
  } catch (err) {
    if (err instanceof DOMException && err.name === "AbortError") {
      console.log("Request was cancelled");
    }
    throw err;
  } finally {
    clearTimeout(timeoutId);
  }
}

Pass the signal to any API that supports it. Most Node.js APIs accept AbortSignal now.

import { readFile } from "node:fs/promises";

const controller = new AbortController();

// Cancel after 1 second
setTimeout(() => controller.abort(), 1000);

try {
  const content = await readFile("/huge/file.txt", {
    signal: controller.signal,
    encoding: "utf-8",
  });
} catch (err) {
  if ((err as NodeJS.ErrnoException).code === "ABORT_ERR") {
    console.log("File read cancelled");
  }
}

Top-Level await

In ESM modules, you can use await at the top level. No wrapper function needed.

// config.ts (ESM module)
const response = await fetch("https://config.example.com/settings");
export const config = await response.json();

// main.ts
import { config } from "./config.js";
// config is already resolved when this module loads
console.log(config.port); // 3000

This works because ESM modules are asynchronous by design. The module system waits for top-level awaits to resolve before making the module available to importers.

Sequential vs Parallel: The Common Mistake

This is the number one async performance bug. Awaiting in a loop runs things one at a time.

// BAD: Sequential. Each request waits for the previous one.
async function fetchAllUsers(ids: string[]) {
  const users = [];
  for (const id of ids) {
    const user = await fetchUser(id); // waits here each iteration
    users.push(user);
  }
  return users;
}
// 10 users, 100ms each = 1000ms total
// GOOD: Parallel. All requests fire at once.
async function fetchAllUsers(ids: string[]) {
  return Promise.all(ids.map((id) => fetchUser(id)));
}
// 10 users, 100ms each = ~100ms total

If you need to limit concurrency (don't fire 10,000 requests at once), batch them:

async function batchProcess<T, R>(
  items: T[],
  fn: (item: T) => Promise<R>,
  batchSize: number
): Promise<R[]> {
  const results: R[] = [];

  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
    const batchResults = await Promise.all(batch.map(fn));
    results.push(...batchResults);
  }

  return results;
}

// Process 100 items, 10 at a time
const results = await batchProcess(userIds, fetchUser, 10);

Key Takeaways

  • async/await is syntactic sugar over Promises. Use it everywhere instead of .then() chains.
  • Promise.all runs things in parallel and fails fast. Promise.allSettled runs in parallel and collects all results.
  • AbortController is your cancellation mechanism. Pass its signal to fetch, file operations, and any API that supports it.
  • Never await inside a loop unless you need sequential execution. Use Promise.all with .map() for parallel work.
  • Top-level await works in ESM modules. Use it for async initialization.
  • Always handle errors. Unhandled rejections crash Node.js.

🎁 Node.js has two module systems that don't play nicely with each other — write a single import wrong and you get a runtime crash that the TypeScript compiler didn't warn you about. Why does this exist, and how do you stay out of trouble?

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

Spot something off? Report an issue