Lesson 18 / 28
async/await
Write asynchronous code that reads like synchronous code.
await pauses, doesn't block
await pauses the surrounding async function until the Promise settles — the rest of Node keeps running.
import { readFile } from "node:fs/promises";
async function loadNotes() {
const data = await readFile("notes.txt", "utf8");
console.log(data.length, "characters");
}
loadNotes();Parallel with Promise.all
Awaiting one call at a time is sequential — use Promise.all to run them together.
async function loadBoth() {
const [notes, config] = await Promise.all([
readFile("notes.txt", "utf8"),
readFile("config.json", "utf8"),
]);
console.log(notes.length, config.length);
}Quick check: What happens to the rest of Node while one function awaits a Promise?
- It freezes completely
- It keeps running other work
- It restarts the event loop
Answer
It keeps running other work — `await` only pauses the current async function — the event loop is free to handle other events meanwhile.