Core Modules & AsyncCore· 35 min read

Async in Node

Callbacks, promises and async/await on the server — essential for databases and file I/O.

What you will learn

  • Recognise the callback pattern
  • Use promises and async/await in Node
  • Handle errors in async code

The same async you know, on the server

Some jobs take time — reading a file, calling a database, fetching from the internet. These slow jobs are often called I/O (Input/Output) — any work where your program reads data in or writes data out, like talking to a disk, a database, or the network. Async (short for asynchronous) code lets Node start a slow I/O job and keep working instead of standing still until it finishes. The async/await you learned for the browser works identically in Node, and you will use it constantly for database queries and file access.

Here is the modern pattern: an async function that awaits a slow operation, wrapped in try/catch to handle any failure:

async/await with try/catch in Node
const fs = require("fs/promises");   // promise-based fs

async function readNote() {
  try {
    const data = await fs.readFile("note.txt", "utf8");
    console.log("File says:", data);
  } catch (err) {
    console.log("Could not read the file:", err.message);
  }
}
readNote();

Note: Output (when the file exists): File says: Hello, file! Output (when it is missing): Could not read the file: ENOENT: no such file or directory, open 'note.txt' How it reads: fs/promises is a version of fs whose methods return promises, so we can await them. await fs.readFile(...) pauses inside this function until the file is read, then puts the text in data. If the read fails (e.g. the file is missing), the error jumps to the catch block, where err.message gives a plain-language reason. The function does not block the rest of the program while it waits.

Note: Older Node code uses callbacks (a function passed in to run when done), which can nest deeply (“callback hell”). Promises and async/await are the modern, readable replacement.

Tip: In Express + MongoDB, almost every database call returns a promise. You will await them inside async route handlers, wrapped in try/catch. Master this pattern now.

Q. What is the modern, readable way to handle async operations in Node?

Answer: async/await (with try/catch for errors) is the modern, readable pattern — used heavily with databases and file I/O.

✍️ Practice

  1. Rewrite a callback-based file read using fs/promises and async/await.
  2. Add try/catch error handling around an await.

🏠 Homework

  1. Write an async function that reads a file and handles the “file not found” error gracefully.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →