Skip to content

Lesson 13 of 14 · 20m

Promise<T> types the success — the error is unknown

fetch resolves on HTTP 500, catch binds unknown, unhandled rejections kill Node, and Promise.all vs allSettled.

Call fetch("/api/rotate-key", { method: "POST" }), get a 500 back, and the await resolves. No rejection, no throw — fetch only rejects on network failure; an HTTP 500 is a successful round-trip. Promise<T> types exactly one thing: the fulfillment value. The rejection channel has no type at all, and most of the bugs in async TypeScript live in that gap.

catch (e) is unknown — correctly

try {
  await rotate();
} catch (e) {
  e.message; // error under strict — e is unknown
}

useUnknownInCatchVariables (in strict since TS 4.4) binds catch (e) as unknown, because the thrown value can be anything — JavaScript lets you throw "string", throw {code: 42}, throw null, and production code does all three. The correct move is to narrow: e instanceof Error before e.message, e re-narrowed for code/status when you handle structured errors. Code that assumed e: any — and there is a lot of it — fails to compile the moment strict lands, which is the flag doing its job.

Promises can't type their errors

There is no Promise<T, E> — JavaScript's promise machinery has no typed rejection path, and async functions have no throws clause to declare. This is why Result-returning APIs exist (the discriminated-union lesson): expected failures return { ok: false, error } where the type system can see them, and throw is reserved for things that are actually exceptional. Libraries like neverthrow package exactly this convention. If a failure is part of the contract — bad input, expired session, quota exceeded — it belongs in the return type, not the reject channel.

Two promise mechanics worth getting right:

const [a, b] = await Promise.all([fetchA(), fetchB()]); // tuple types preserved
const settled = await Promise.allSettled(tasks);        // {status, value|reason}[]

Promise.all preserves tuple types per position and rejects on the first failure — the other promises keep running, unobserved. allSettled waits for everything and gives each outcome a status discriminant — the right tool when partial success is real (fan-out cleanup, multi-tenant jobs). Promise.race returns the first settled, fulfilled or rejected — a race between an operation and a timeout that rejects is the standard cancellation idiom, though AbortSignal.timeout(ms) now does it natively for fetch and anything that takes a signal.

Floating promises and the crash they cause

async function handler() { await writeAudit(...); }
handler(); // returns a promise nobody awaited

An unawaited promise is a floating promise: errors in it never reach a catch, and since Node 15 an unhandled rejection kills the process (--unhandled-rejections=throw is the default). A floating promise in a request handler is a remote process-kill. The practical fixes: await or return every promise, mark deliberate fire-and-forget with void promise;, and let typescript-eslint's no-floating-promises rule enforce it — it's a lint rule because the compiler itself doesn't flag floating promises.

Also know: await on a non-promise just wraps it (await 5 is 5), async functions always return a promise even when the body is synchronous, and .catch(() => {}) on a floating promise swallows errors deliberately — fine when silence is the design, never when it's a shrug.

Try this

Take an async handler that does catch (e: any). Rebind to catch (e), narrow with instanceof Error, and route the expected-failure paths — expired token, validation — into a returned Result. Then grep for handler(); call sites with no await and no void and decide which were accidents.

Pitfalls

  • res.ok before res.json() — fetch resolves on 4xx/5xx; a non-ok response parsed as JSON is a runtime bug in the success path.
  • Promise.all rejects fast but doesn't cancel the losers; for real cancellation, wire AbortController signals through.
  • forEach(async ...) doesn't await — it fires N promises and moves on. for...of awaits serially; Promise.all(map) awaits concurrently.
  • await inside try only catches rejections of that await — a promise stored earlier and awaited elsewhere throws at its await site, not its creation site.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.