Skip to content

Promises and async

Relay talks to a queue, an upstream API and a notifier. Every one of those calls is asynchronous, and every one can be slow or fail. If the wrapper around such a call returns Promise<any>, the caller loses the result type exactly where mistakes are most likely.

This lesson types async code, then builds two wrappers every Relay call will use: withTimeout and retry. Both keep the type of whatever they wrap.

A Promise<T> is a value that will become a T, or fail. An async function always returns a promise, so its return type is wrapped for you:

interface Job {
readonly id: string
readonly status: "queued" | "running" | "failed" | "succeeded"
readonly queuedAt: number
}
async function getJob(id: string): Promise<Job> {
return { id, status: "queued", queuedAt: 0 }
}
async function jobCount() {
return 3 // inferred: Promise<number>
}
async function main() {
const job = await getJob("j1") // Job
const n = await jobCount() // number
return [job, n]
}

await unwraps one promise. The built-in Awaited<T> does the same at the type level and also unwraps promises nested inside promises. Awaited<Promise<Promise<number>>> is number. M4 shows how it is built.

Promise.all takes a tuple of promises and returns a promise of a tuple. Each position keeps its own type:

interface Job {
readonly id: string
}
interface Worker {
readonly name: string
}
declare function getJob(id: string): Promise<Job>
declare function listWorkers(): Promise<Worker[]>
async function main() {
const [job, workers] = await Promise.all([getJob("j1"), listWorkers()])
job.id // job is Job
workers.length // workers is Worker[]
}

The calls start together, so this takes as long as the slowest one. If any promise rejects, Promise.all rejects with that error and the other results are thrown away.

When Relay should keep going after a failure, use Promise.allSettled. It never rejects. Each result is a union, discriminated by status, so the same narrowing you know from M2 applies:

declare const tasks: Promise<number>[]
async function main() {
const results = await Promise.allSettled(tasks)
for (const r of results) {
if (r.status === "fulfilled") {
r.value // number
} else {
r.reason // any
}
}
}

A promise has no error type. Promise<Job> says what success looks like and nothing about failure. A catch variable is unknown under strict, and PromiseRejectedResult.reason is any. Treat both as unknown and narrow before use, as in unknown. When you want the error in the type, return a value instead, as in errors as values.

async function run(task: () => Promise<number>): Promise<string> {
try {
return String(await task())
} catch (error) {
// @ts-expect-error: error is unknown, not Error
return error.message
}
}

Calling an async function without await or .catch starts it and forgets it. If it rejects, the error has nowhere to go:

declare function notify(jobId: string): Promise<void>
async function onFailed(jobId: string) {
notify(jobId) // floating: a failure here is never seen
await notify(jobId) // the error reaches the caller
}

The compiler does not flag this. The lint rule @typescript-eslint/no-floating-promises does.

withTimeout races a task against a timer. The result type is the task’s type, so it is generic:

class TimeoutError extends Error {
readonly _tag = "TimeoutError"
constructor(readonly ms: number) {
super(`timed out after ${ms}ms`)
}
}
function withTimeout<T>(task: Promise<T>, ms: number): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new TimeoutError(ms)), ms)
})
return Promise.race([task, timeout]).finally(() => clearTimeout(timer))
}

The timeout is a Promise<never>: it never resolves, so it adds nothing to the result type. Promise.race([Promise<T>, Promise<never>]) is Promise<T>. The finally clears the timer. Without it, every successful call leaves a timer alive until it fires.

retry calls a function again when it fails. It takes the function, not a promise, because a promise has already started and cannot be run again. The T flows from the task to the result:

interface RetryOptions {
attempts: number
delayMs: (attempt: number) => number
sleep: (ms: number) => Promise<void>
shouldRetry?: (error: unknown) => boolean
}
async function retry<T>(task: () => Promise<T>, options: RetryOptions): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await task()
} catch (error) {
if (attempt >= options.attempts || options.shouldRetry?.(error) === false) throw error
await options.sleep(options.delayMs(attempt))
}
}
}
declare function fetchQueueDepth(): Promise<number>
const depth = retry(fetchQueueDepth, {
attempts: 3,
delayMs: (n) => 100 * n,
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
})
// depth: Promise<number>

sleep is a parameter on purpose. Production passes a real timer. A test passes a function that records the delay and returns at once, so a test of three retries does not take seconds. This is the same rule as passing the time in: the logic does not reach for the clock itself.

Write withTimeout, TimeoutError, retry and settle. The starter types everything as Promise<any>, makes one attempt too few and never sleeps. The rules at the top say exactly when retry sleeps and which delay it asks for.

  • async wraps the return type in Promise. await and Awaited<T> unwrap it.
  • Promise.all keeps one type per position. allSettled gives a union you narrow by status.
  • A rejection has no type. Treat it as unknown.
  • An un-awaited promise loses its error.
  • Wrappers like withTimeout<T> and retry<T> pass T through, so the caller keeps its type.
  • Take sleep as a parameter so retry logic is testable without waiting.