Node.js Async
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:
- Read two files concurrently using
fs.readFilefromnode:fs/promisesandPromise.all(). - Wrap an
awaitcall intry / catchand handle a rejected Promise gracefully. - Explain why calling
JSON.parseon a 50 MB payload on the main thread hurts HTTP throughput.