Skip to content

Promises

A promise is a value that will be available later. In TypeScript it is also a type with one parameter: Promise<T> fulfils with T. What the type cannot express is when or whether it will settle, which is where the interesting bugs live.

“A Promise<T> is pending, fulfilled with T, or rejected with a reason typed as unknown. then maps a fulfilment value and returns a new promise, catch handles a rejection, finally runs on both paths without changing the result. async functions always return a promise, and await unwraps one level and throws on rejection, which is why try/catch works. Promise.all requires all results, allSettled tolerates failures, race takes the first to settle and any the first to succeed. The type system tracks the value type but not the sequencing, the cancellation, or the error type unless you annotate it.”

type FetchState<T> =
| { status: 'pending' }
| { status: 'fulfilled'; value: T }
| { status: 'rejected'; reason: unknown };

A promise object exposes only then, catch and finally — there is no .state or .value property. Reading the result requires a continuation, which is the point: the value is only safe to use inside a handler. Promise<T> is covariant in T, so a Promise<string> is assignable to a Promise<string | number>; that is fine for reading and irrelevant when you accumulate into arrays.

chain.ts
interface User { id: string; name: string }
fetch('/api/user/1')
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<User>; // returning a promise flattens it
})
.then((user) => user.name)
.catch((err: unknown) => (err instanceof Error ? err.message : 'unknown error'))
.finally(() => console.log('settled'));

Typing notes:

  • then is generic: .then<U>(fn: (value: T) => U | PromiseLike<U>) returns Promise<U>, so the chain type is derived and intermediate annotations are usually unnecessary.
  • A catch callback receives unknown under strict, which forces a check before .message.
  • finally takes no value and returns Promise<T>; it cannot change the result unless it throws.
  • .json() in the DOM lib returns Promise<any>. Assert or, better, validate. The cast is a claim the compiler cannot verify.
combinators.ts
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]); // [User, Post[]]
const settled = await Promise.allSettled([fetchUser(), fetchPosts()]);
for (const r of settled) {
if (r.status === 'fulfilled') console.log(r.value);
else console.error(r.reason);
}
const fastest = await Promise.any([mirrorA(), mirrorB()]); // User
Method Resolved type Rejects with
Promise.all Tuple or T[] First rejection reason
Promise.allSettled PromiseSettledResult<T>[] Never
Promise.race Union of all types First settled, either way
Promise.any Union of all types AggregateError

Promise.all on a tuple preserves positions, which is why destructuring works without casts. Pass a non-tuple array and you get (A | B)[]. Promise.any’s AggregateError carries each reason in .errors; the type models it as a plain error, so narrow at runtime.

async.ts
async function loadUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new HttpError(res.status);
return (await res.json()) as User;
}
async function loadAll(ids: string[]): Promise<User[]> {
return Promise.all(ids.map(loadUser));
}

async wraps a returned value in a promise and converts a thrown error into a rejection. Returning a promise from an async function flattens it, so Promise<Promise<T>> never materialises. Awaited<T> unwraps nested promises and is the right tool in generic helpers.

mistakes.ts
fetch('/api/save', { method: 'POST' }); // 1. floating promise: errors escape
for (const id of ids) await loadUser(id); // 2. sequential where parallel is possible
ids.forEach(async (id) => { await loadUser(id); }); // 3. forEach ignores the promise
try { fetch('/api/x'); } catch { /* never runs */ } // 4. catch around an unawaited promise
catch (e) { e.message; } // 5. error: 'e' is unknown
new Promise((resolve) => resolve(fetchUser())); // 6. wrapping an existing promise

Turn on no-floating-promises and no-misused-promises in typescript-eslint. They catch most of the above, which the type system itself cannot.

  1. Why does res.json() return Promise<any>, and what should you do about it?
  2. What is the difference between Promise<void> and void?
  3. Why is Promise<T> covariant, and where does that bite?
  4. How do you type the rejection reason when unknown is not enough?
  • Assuming the type guarantees success. Promise<User> says nothing about HTTP status; fetch resolves on 404 and 500 too.
  • Not checking res.ok. The most common bug in typed fetch wrappers.
  • as instead of validation. The cast is erased; the data is not what you claimed.
  • await in map without Promise.all. You get an array of promises, not of values.
  • Catching unknown and calling .message. Narrow with instanceof Error first.
  • Using Promise.race as a timeout without cancelling. The loser keeps running.