Beginner Fundamentals

Async and Await

async and await are syntax built on top of Promises. They let you write asynchronous code that looks and reads like normal step by step code.

The basics

Mark a function async, then use await to pause until a Promise resolves.

const fs = require("fs/promises");

async function showFile() {
  const data = await fs.readFile("note.txt", "utf8");
  console.log(data);
}

showFile();

await only works inside an async function.

Handling errors with try/catch

Because the code reads top to bottom, you can use a regular try/catch:

const fs = require("fs/promises");

async function showFile() {
  try {
    const data = await fs.readFile("missing.txt", "utf8");
    console.log(data);
  } catch (err) {
    console.error("Could not read file:", err.message);
  }
}

showFile();

Returning values

An async function always returns a Promise:

async function getNumber() {
  return 42;
}

getNumber().then((n) => console.log(n)); // 42

Summary

async/await is the modern, readable way to handle async code. Use await for Promises and wrap risky calls in try/catch.