Node.js Async

Async behavior is central to Node. Learn how the event loop, promises, and async functions keep I/O responsive.

Event loop

Node.js executes your JavaScript on a single main thread and delegates non-blocking I/O (network sockets, timers, filesystem reads) to the OS kernel and libuv thread pool. As soon as an I/O call finishes, its callback or Promise reaction is queued on the event loop. Because one thread serves all concurrent requests, running synchronous CPU loops or fs.readFileSync inside an active server stalls every other client.

Promises

A Promise represents a future value that settles once as either fulfilled or rejected. Prefer built-in Promise-based APIs such as node:fs/promises or node:timers/promises instead of wrapping callback APIs manually:

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

wait(50).then(() => console.log("timer settled"));

async/await

async functions let you write Promise chains as sequential steps with standard try / catch error handling. Watch for accidental serialization: awaiting two independent I/O calls one after another doubles total latency, whereas Promise.all() runs them concurrently:

async function run() {
  try {
    // Run independent async operations concurrently instead of sequentially
    const [a, b] = await Promise.all([wait(100), wait(100)]);
    console.log("done in ~100ms", a, b);
  } catch (err) {
    console.error("Async step failed:", err);
  }
}

run();

Practice

Test concurrency and error handling with Promises:

  1. Read two files concurrently using fs.readFile from node:fs/promises and Promise.all().
  2. Wrap an await call in try / catch and handle a rejected Promise gracefully.
  3. Explain why calling JSON.parse on a 50 MB payload on the main thread hurts HTTP throughput.