Level 16
Async Programming
TypeScript types asynchronous code precisely: Promise<T> captures what a promise resolves to, async/await keeps that typing through readable control flow, and Awaited<T> models unwrapping in generic code.
25 min read + quiz
Promise<T>: A Typed Future Value
A Promise<T> is a value that will eventually resolve to a T (or reject). The type parameter is the whole story for TypeScript: fetchUser returning Promise<User> means await fetchUser() is a User, and .then callbacks receive a User. Get the parameter right and everything downstream is typed for free.
Note what is not typed: the rejection. Promises can reject with anything, so TypeScript makes no attempt to track error types — a caught error is unknown. Plan for this by narrowing in catch blocks (err instanceof Error) rather than assuming a shape.
A frequent mistake is declaring Promise<void> when you actually resolve with data, or forgetting that an async function's return value is always wrapped: writing return user inside async function f(): Promise<User> is correct — you never wrap it yourself with Promise.resolve.
interface User {
id: number;
name: string;
}
function fetchUser(id: number): Promise<User> {
// Simulated network call.
return new Promise((resolve) => {
setTimeout(() => resolve({ id, name: "User " + id }), 10);
});
}
async function main(): Promise<void> {
const user = await fetchUser(1); // user: User
console.log(user.name);
}The type parameter flows from the promise to every await.
async/await and Error Handling
async/await is syntax over promises: await pauses the async function until the promise settles, and a rejected promise becomes a thrown exception at the await site. This lets you use ordinary try/catch and finally around asynchronous work.
Under strict settings the caught value is typed unknown, which is honest — anything can be thrown. The robust pattern is to narrow immediately: check err instanceof Error for the message, or use a custom error class with instanceof to carry structured data like HTTP status codes.
The subtlest bug in async error handling is forgetting to await. If you return or ignore a promise inside try, rejections escape the catch block entirely, because the function has already left the try by the time the promise rejects. Enable the no-floating-promises lint rule; it catches these reliably.
class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
async function loadProfile(id: number): Promise<string> {
try {
const user = await fetchProfile(id);
return user;
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
return "Profile not found";
}
throw err; // rethrow what we cannot handle
}
}
async function fetchProfile(id: number): Promise<string> {
if (id <= 0) throw new ApiError(404, "no such user");
return "profile-" + id;
}Narrow unknown errors with instanceof; rethrow what you can't handle.
Running Work Concurrently
Sequential awaits serialize independent work: await a(); await b(); takes the sum of both durations. When the operations do not depend on each other, start them first and await together with Promise.all — the total becomes the slowest one instead of the sum. This is the single highest-impact async optimization in typical applications.
Promise.all is precisely typed via tuples: Promise.all([pUser, pOrders]) resolves to [User, Order[]], so destructuring keeps full types. Its failure mode is all-or-nothing — one rejection rejects the whole thing. When you want every result regardless of failures, Promise.allSettled returns a typed array of { status: 'fulfilled', value } | { status: 'rejected', reason } objects you can filter.
Promise.race resolves with the first settled promise, useful for timeouts. Be careful racing anything with side effects: the losing promise keeps running — race only affects which result you observe, not what work happens.
async function getUserName(): Promise<string> {
return "Ada";
}
async function getOrderCount(): Promise<number> {
return 3;
}
async function dashboard(): Promise<string> {
// Both start immediately; total time = max, not sum.
const [name, count] = await Promise.all([
getUserName(),
getOrderCount(),
]);
// name: string, count: number — tuple typing preserved.
return name + " has " + count + " orders";
}
async function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
const timeout = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error("Timed out")), ms);
});
return Promise.race([p, timeout]);
}Promise.all preserves tuple types; Promise<never> makes race's type work out.
Awaited<T> and Generic Async Code
Awaited<T> answers the question 'what type does await produce for a T?'. It unwraps Promise<string> to string, recursively flattens Promise<Promise<string>> to string, and leaves non-promises alone. The standard library uses it to type Promise.all and friends.
You need it when writing generic helpers over async functions. Given fn: () => T where T might be a promise, the result of awaiting fn() is Awaited<T> — writing T there is wrong because await never yields a promise. This distinction only appears in generic code, which is why many developers first meet Awaited in a confusing error message.
A related trap: an array of async calls like urls.map(async (u) => load(u)) is a Promise<Item>[] — an array of promises, not a promise of an array. You must wrap it in Promise.all to await it meaningfully. The types make this mistake visible if you read them carefully.
type A = Awaited<Promise<string>>; // string
type B = Awaited<Promise<Promise<number>>>; // number (recursive)
type C = Awaited<boolean>; // boolean (non-promise untouched)
async function runAll<T extends readonly (() => unknown)[]>(
fns: T
): Promise<{ [K in keyof T]: Awaited<ReturnType<T[K]>> }> {
return Promise.all(fns.map((fn) => fn())) as Promise<{
[K in keyof T]: Awaited<ReturnType<T[K]>>;
}>;
}
// const [s, n] = await runAll([async () => "hi", async () => 42] as const);
// s: string, n: numberAwaited models what the await keyword actually does.
Floating Promises and void Returns
A floating promise is one that is created but never awaited or handled. Its rejection becomes an unhandled rejection — a crash in modern Node — and its completion order is unobservable. TypeScript itself does not flag these; the typescript-eslint rule no-floating-promises does, and every serious codebase should enable it.
There are legitimate fire-and-forget cases (logging, analytics). Make them explicit with the void operator — void trackEvent('click') — which signals intent to both readers and the linter, and attach a .catch for safety where failure matters even a little.
Also distinguish Promise<void> from void: an async function with no meaningful result returns Promise<void>, and callers should still await it to observe errors and ordering. Declaring a callback type as () => void, however, permits an async function to be passed — its promise gets discarded silently, which is exactly how unawaited handlers sneak into event systems.
async function save(): Promise<void> {
// pretend to write to a database
}
async function handler(): Promise<void> {
save(); // floating! rejection would be unhandled
await save(); // correct: errors propagate, order guaranteed
// Explicit fire-and-forget, intent visible:
void save();
}
// Danger zone: () => void accepts async functions silently.
function onClick(cb: () => void): void {
cb();
}
onClick(async () => {
await save(); // this promise is discarded by onClick
});await by default; use the void operator to mark intentional fire-and-forget.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
Why is a caught error typed as unknown in a try/catch around await, rather than Error?
Question 2 · Predict the output
What does this program print?
async function getValue(): Promise<number> {
return 5;
}
const result = getValue();
console.log(typeof result, result instanceof Promise);Question 3 · Find the error
This code is meant to catch failures from save(), but rejections escape the catch. Why?
async function save(): Promise<void> {
throw new Error("disk full");
}
async function run(): Promise<void> {
try {
save();
} catch (err) {
console.log("handled:", err);
}
}Question 4 · True or false
If one promise passed to Promise.all rejects, the other promises are automatically cancelled.
Question 5 · Multiple choice