Skip to content

Lesson 6 of 9 · 25m

Async Pipelines: Promise, Result, and Cancellation

Compose asynchronous operations without losing error context, race metadata, or cancellation semantics.

When a pipeline becomes asynchronous, JavaScript adds two kinds of failure: the operation can fail, and the pipeline can become irrelevant before it finishes. Teams often handle the first with catch and ignore the second. Production FP treats async as data flow over time, not synchronous composition with await sprinkled in.

Names beat clever chaining

async function loadDashboard(userId) {
  const user = await fetchUser(userId);
  const entitlements = await fetchEntitlements(user.accountId);
  return buildDashboard(entitlements);
}

then chains are composition too, but named intermediate values are easier to debug. The functional part is not the syntax; it is keeping each step explicit and pushing effects into named operations.

Promise rejection is not typed failure

fetchJson can reject with abort errors, network errors, parse bugs, or HTTP failures. Expected API failures deserve a Result shape:

async function getUserResult(id, signal) {
  try {
    const res = await fetch(`/api/users/${id}`, { signal });
    if (res.status === 404) return err({ code: "missing" });
    if (!res.ok) return err({ code: "http", status: res.status });
    return ok(await res.json());
  } catch (e) {
    if (e.name === "AbortError") return err({ code: "cancelled" });
    throw e; // unexpected environment or programmer failure
  }
}

This preserves context instead of flattening everything into "Something went wrong."

Cancellation is part of correctness

let latest = 0;
async function runSearch(query) {
  const mine = ++latest;
  const result = await search(query);
  if (mine !== latest) return; // stale response
  renderResults(result);
}

The slow response for an old query must not overwrite the fast response for the current one. AbortController is the transport-level half of the solution; a sequence guard is the application-level half.

Concurrency needs intent

Promise.all fails fast. Promise.allSettled collects partial outcomes. Sequential awaits are correct when ordering or rate limits matter. Once third-party quotas enter the picture, an explicit concurrency limit beats elegant composition.

Field notes

  • Cancelled is not the same as failed; do not store AbortError as a user-visible error.
  • Attach operation names or IDs before crossing async boundaries. Stack traces often stop at await.
  • finally runs after cancellation too; do not use it as proof of success.
  • Standardize async error shapes before adding more abstraction.

Was this lesson helpful?

Sign in to rate