Async TypeScript

View saved

Type a Promise

Annotate what a promise resolves to with Promise<T>.

function wait(ms: number): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => resolve("done"), ms);
  });
}

wait(10).then(console.log);

Use async and await

An async function always returns a Promise. Await unwraps the value with its type.

async function loadTitle(): Promise<string> {
  return "TypeScript";
}

async function main() {
  const title = await loadTitle();
  console.log(title.toUpperCase());
}

main();

Handle failures

Wrap awaits in try/catch. Error values are often unknown.

async function safe() {
  try {
    await Promise.reject(new Error("boom"));
  } catch (err: unknown) {
    if (err instanceof Error) {
      console.error(err.message);
    }
  }
}

Async typing tips

  • Prefer async/await over long .then chains while learning
  • Type fetch wrappers to return interfaces you define
  • Do not ignore rejected promises
  • Remember async functions return promises even if you return a plain value

Comments

One comment per signed-in account. Comments are saved with this page’s URL.