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.
Promise<T> and async
Section titled “Promise<T> and async”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 keeps a tuple
Section titled “Promise.all keeps a tuple”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.
Promise.allSettled and status
Section titled “Promise.allSettled and status”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 } }}Rejections are not typed
Section titled “Rejections are not typed”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 }}Floating promises
Section titled “Floating promises”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.
A typed timeout
Section titled “A typed timeout”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.
A typed retry
Section titled “A typed retry”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.
Exercise
Section titled “Exercise”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.
asyncwraps the return type inPromise.awaitandAwaited<T>unwrap it.Promise.allkeeps one type per position.allSettledgives a union you narrow bystatus.- A rejection has no type. Treat it as
unknown. - An un-awaited promise loses its error.
- Wrappers like
withTimeout<T>andretry<T>passTthrough, so the caller keeps its type. - Take
sleepas a parameter so retry logic is testable without waiting.
Further reading
Section titled “Further reading”- Promise (MDN): promise states and chaining.
- Promise.all() (MDN): combining promises and rejection behaviour.
- Promise.allSettled() (MDN): settled results and their
status. - TypeScript 4.5 release notes: the
Awaitedtype.