Promises and async
Overview
Almost every real program waits for something: a network request, a database query, a file, a timer. JavaScript models these with promises and async/await. TypeScript adds types to the value a promise will eventually produce, so the result of every await is checked just like ordinary code.
Promise
A Promise<T> is a promise that will resolve to a value of type T (or reject with an error):
const later: Promise<number> = new Promise((resolve) => {
setTimeout(() => resolve(42), 1000);
});
const n = await later; // n: numberresolve only accepts a T: resolve("42") would be an error. When TypeScript can’t infer T from context, give it explicitly: new Promise<number>(…).
async functions
An async function always returns a promise, so its return type is Promise<…>:
async function getUserName(id: number): Promise<string> {
const user = await fetchUser(id); // user: User
return user.name; // returns string → the function returns Promise<string>
}Inside, you return a plain string; TypeScript wraps it in the promise. Writing : string as the return type of an async function is an error:
error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<string>'?A function that returns nothing is Promise<void>.
await unwraps
await turns Promise<T> into T. If you forget it, the types catch the mistake as soon as you use the value:
const user = fetchUser(1); // Promise<User> — oops, no await
console.log(user.name);
// error TS2339: Property 'name' does not exist on type 'Promise<User>'.Other forgotten-await cases compile but behave wrongly — for example if (isAdmin(user)) where isAdmin is async (a promise object is always truthy). Linters catch those (@typescript-eslint/no-floating-promises and no-misused-promises, see Linting and formatting).
Running things in parallel
Sequential awaits wait for each step before starting the next:
const user = await fetchUser(1); // 20 ms
const orders = await fetchOrders(1); // + 30 msIf the requests don’t depend on each other, start them together with Promise.all. TypeScript types the result as a tuple, one position per promise:
const [user, orders] = await Promise.all([fetchUser(1), fetchOrders(1)]);
// user: User, orders: Order[] — total time ≈ the slowest oneIf any promise rejects, Promise.all rejects immediately. When you want every result regardless, use Promise.allSettled, which returns a discriminated union per item:
const results = await Promise.allSettled([fetchUser(1), fetchUser(99)]);
for (const r of results) {
if (r.status === "fulfilled") console.log(r.value.name); // r.value: User
else console.log("failed:", r.reason); // r.reason: any
}Promise.race resolves or rejects with the first promise to settle — useful for timeouts — and Promise.any with the first to succeed.
Typing callbacks that are async
A callback type that returns a promise is written like any other function type:
type Handler = (request: Request) => Promise<Response>;
type Task = () => Promise<void>;
async function runAll(tasks: Task[]): Promise<void> {
for (const task of tasks) await task();
}Errors in async code
A rejected promise behaves like a thrown exception: await throws it. And as with try/catch everywhere, the error is unknown, because anything can be rejected:
try {
await fetchUser(99);
} catch (error) {
// error: unknown
console.log(error instanceof Error ? error.message : String(error));
}There’s no way to declare which errors a promise can reject with. If callers need to handle failures as part of normal flow, return a Result instead of rejecting (Error handling).
fetch and JSON
fetch is typed by the DOM and Node type definitions, but the body’s JSON isn’t — response.json() returns Promise<any>:
const response = await fetch("https://api.example.com/users/1");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json(); // any!You could write (await response.json()) as User, but that’s an unchecked assertion: if the API changes, your types lie. The safe approach is to treat the data as unknown and validate it — the subject of Validating external data:
async function getJson(url: string): Promise<unknown> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
return response.json();
}Top-level await
In ES modules you can await at the top level of a file — no wrapping async function main() needed. This course’s projects use it (it requires module: "nodenext" or esnext and a modern target).
Remember: async functions return
Promise<T>,awaitgives youT,Promise.allgives you a typed tuple — and caught or rejected errors areunknown.
A dashboard loader
Using the fake API in the starter (functions that resolve after a delay): (1) write loadDashboard(userId: number): Promise<Dashboard> that loads the user and their orders in parallel with Promise.all, and returns { user, orders, total }; (2) write withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> that rejects with Error("Timed out after <ms>ms") if the promise is too slow; (3) use Promise.allSettled to load users 1, 2 and 99 (99 fails) and print Asha, Ben and failed: User 99 not found. Print the dashboard for user 1 and the result of withTimeout(slow(), 50), catching the error. Use top-level await.
type User = { id: number; name: string };
type Order = { id: string; userId: number; amount: number };
type Dashboard = { user: User; orders: Order[]; total: number };
const delay = <T,>(value: T, ms: number): Promise<T> =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const USERS: User[] = [{ id: 1, name: "Asha" }, { id: 2, name: "Ben" }];
const ORDERS: Order[] = [
{ id: "o1", userId: 1, amount: 40 },
{ id: "o2", userId: 1, amount: 25.5 },
{ id: "o3", userId: 2, amount: 10 },
];
async function fetchUser(id: number): Promise<User> {
const user = USERS.find((u) => u.id === id);
if (!user) throw new Error(`User ${id} not found`);
return delay(user, 20);
}
function fetchOrders(userId: number): Promise<Order[]> {
return delay(ORDERS.filter((o) => o.userId === userId), 30);
}
const slow = () => delay("done", 200);
// 1. loadDashboard
// 2. withTimeout
// 3. allSettledtype User = { id: number; name: string };
type Order = { id: string; userId: number; amount: number };
type Dashboard = { user: User; orders: Order[]; total: number };
const delay = <T,>(value: T, ms: number): Promise<T> =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const USERS: User[] = [{ id: 1, name: "Asha" }, { id: 2, name: "Ben" }];
const ORDERS: Order[] = [
{ id: "o1", userId: 1, amount: 40 },
{ id: "o2", userId: 1, amount: 25.5 },
{ id: "o3", userId: 2, amount: 10 },
];
async function fetchUser(id: number): Promise<User> {
const user = USERS.find((u) => u.id === id);
if (!user) throw new Error(`User ${id} not found`);
return delay(user, 20);
}
function fetchOrders(userId: number): Promise<Order[]> {
return delay(ORDERS.filter((o) => o.userId === userId), 30);
}
const slow = () => delay("done", 200);
// 1. loadDashboard
async function loadDashboard(userId: number): Promise<Dashboard> {
const [user, orders] = await Promise.all([fetchUser(userId), fetchOrders(userId)]);
const total = orders.reduce((sum, order) => sum + order.amount, 0);
return { user, orders, total };
}
// 2. withTimeout
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
// 3. allSettled
const dashboard = await loadDashboard(1);
console.log(dashboard.user.name, dashboard.orders.length, dashboard.total); // Asha 2 65.5
try {
console.log(await withTimeout(slow(), 50));
} catch (error) {
console.log(error instanceof Error ? error.message : error); // Timed out after 50ms
}
const results = await Promise.allSettled([fetchUser(1), fetchUser(2), fetchUser(99)]);
for (const result of results) {
if (result.status === "fulfilled") {
console.log(result.value.name);
} else {
console.log("failed:", result.reason instanceof Error ? result.reason.message : result.reason);
}
}Summary
Promise<T>is a value of type T that arrives later;awaitunwraps it to T.- An
asyncfunction always returns aPromise— annotate it asPromise<T>. Promise.all([a, b])returns a typed tuple;Promise.allSettledreturns typed fulfilled/rejected results.- Rejections are untyped: errors from
awaitand.catchareunknownand must be narrowed. - Don’t forget
await— a forgotten promise is a bug TypeScript and linters can catch.