Async and Await

View saved

Why async matters

File I/O, network calls, and timers finish later. Blocking the event loop freezes the whole process.

Await a promise

Mark the function async, then await work that returns a promise.

import { readFile } from "fs/promises";

async function main() {
  const text = await readFile("notes.txt", "utf8");
  console.log(text);
}

main();

Run work in parallel

Start several promises, then wait together.

const [a, b] = await Promise.all([
  readFile("a.txt", "utf8"),
  readFile("b.txt", "utf8"),
]);

Remember top-level await

In ES modules you can await at the top level. In CommonJS, wrap in an async main.

Comments

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