Promises and async

Topic 1 of 3 in Async code and runtime safety7 min readIntermediateFree course

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):

TypeScript
const later: Promise<number> = new Promise((resolve) => {
  setTimeout(() => resolve(42), 1000);
});

const n = await later;   // n: number

resolve 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

Typing async code. async function loadUser(id: number): Promise<User> { const res = await fetch(/api/users/${id}); return (await res.json()) as User; } — an async function always returns a Promise, and json() gives any (see “Validating external data”). loadUser(1) is Promise<User> — the promise itself. await loadUser(1) is User — await unwraps it. Promise.all([loadUser(1), loadPosts(1)]) is Promise<[User, Post[]]> — a typed tuple of results. Forgetting await is a common bug: TypeScript spots it when you use a Promise<User> where a User is expected.

An async function always returns a promise, so its return type is Promise<…>:

TypeScript
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:

Text
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:

TypeScript
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:

TypeScript
const user = await fetchUser(1);        // 20 ms
const orders = await fetchOrders(1);    // + 30 ms

If 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:

TypeScript
const [user, orders] = await Promise.all([fetchUser(1), fetchOrders(1)]);
// user: User, orders: Order[] — total time ≈ the slowest one

If any promise rejects, Promise.all rejects immediately. When you want every result regardless, use Promise.allSettled, which returns a discriminated union per item:

TypeScript
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:

TypeScript
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:

TypeScript
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>:

TypeScript
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:

TypeScript
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>, await gives you T, Promise.all gives you a typed tuple — and caught or rejected errors are unknown.

Exercise

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.

TypeScript
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. allSettled

Summary

  • Promise<T> is a value of type T that arrives later; await unwraps it to T.
  • An async function always returns a Promise — annotate it as Promise<T>.
  • Promise.all([a, b]) returns a typed tuple; Promise.allSettled returns typed fulfilled/rejected results.
  • Rejections are untyped: errors from await and .catch are unknown and must be narrowed.
  • Don’t forget await — a forgotten promise is a bug TypeScript and linters can catch.