Asynchronous Node: Callbacks, Promises, Sync APIs and the Event Loop Phases
Why Node is non-blocking by default and how to use its three API styles: error-first callbacks, promise APIs and util.promisify, and Sync functions. Then the event loop's phases, process.nextTick vs microtasks, setImmediate vs setTimeout, blocking pitfalls and the libuv thread pool.
kvi5hnuCode Sprout team member7 min readOn this page
A Node server may handle thousands of connections at once on one JavaScript thread. It manages this because almost every operation that waits, such as reading a file, querying a database, or receiving network data, is non-blocking: Node starts the operation, keeps running other code, and calls you back when the result is ready. This article covers the API styles Node offers for asynchronous work, and the event loop that drives them.
Single-threaded, but concurrent
Your JavaScript runs on a single thread, so there are no data races between your own functions: a function always runs to completion before any other callback starts (article 94). Waiting happens elsewhere:
- Network I/O uses the operating system's non-blocking facilities (epoll, kqueue, IOCP) through libuv.
- File system operations, DNS lookups, compression and some crypto functions run on libuv's thread pool (4 threads by default; set
UV_THREADPOOL_SIZEto change it), because operating systems don't offer portable non-blocking versions of them.
This model is excellent for I/O-heavy programs like web servers and API gateways. It's bad at long CPU-bound computations, which block everything; those belong in worker threads (article 131) or separate processes (article 130).
Three API styles
Node grew up before promises existed, so many modules offer the same operation in up to three forms. Reading a configuration file all three ways:
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "config-"));
const file = path.join(dir, "config.json");
fs.writeFileSync(file, '{ "port": 8080, "debug": true }');
// 1. Error-first callback: the last argument is called with (err, result)
function readConfigCallback(filename, callback) {
fs.readFile(filename, "utf8", (err, text) => {
if (err) return callback(err);
let config;
try {
config = JSON.parse(text);
} catch (parseError) {
return callback(parseError);
}
callback(null, config);
});
}
// 2. Promises, from the node:fs/promises module
async function readConfig(filename) {
return JSON.parse(await fsp.readFile(filename, "utf8"));
}
// 3. Synchronous: blocks until done, throws on error
function readConfigSync(filename) {
return JSON.parse(fs.readFileSync(filename, "utf8"));
}
console.log("sync:", readConfigSync(file));
readConfigCallback(path.join(dir, "missing.json"), (err, config) => {
console.log("callback:", err ? err.code : config);
readConfig(file).then((config) => {
console.log("promise:", config.port);
fs.rmSync(dir, { recursive: true });
});
});
console.log("callback requested; this line runs first");
sync: { port: 8080, debug: true }
callback requested; this line runs first
callback: ENOENT
promise: 8080
Error-first callbacks
The classic Node convention: the last argument is a callback, called with an error (or null) first, then the result. Every callback must check the error before using the result, and errors must be passed to the callback rather than thrown, because a throw inside an asynchronous callback can't be caught by the caller's try/catch. Note also how JSON.parse needed its own try/catch inside the callback. Error objects from the system carry a code such as ENOENT (no such file), EACCES (permission denied) or EADDRINUSE (port in use).
Promise APIs
Most modules now have promise versions: node:fs/promises, node:dns/promises, node:stream/promises, node:timers/promises (with await setTimeout(ms)), node:readline/promises. With async/await, errors become ordinary exceptions caught by try/catch, which makes promises the right default for new code.
For callback-style functions without a promise version, util.promisify converts any function that follows the error-first convention, and util.callbackify goes the other way:
const util = require("node:util");
// An old-style function with an error-first callback
function divideLater(a, b, callback) {
setTimeout(() => {
if (b === 0) callback(new RangeError("division by zero"));
else callback(null, a / b);
}, 5);
}
const divide = util.promisify(divideLater);
async function main() {
console.log(await divide(10, 4));
try {
await divide(1, 0);
} catch (err) {
console.log(err.name, err.message);
}
// The reverse: give a promise-returning function a callback interface
const legacyDouble = util.callbackify(async (n) => n * 2);
legacyDouble(21, (err, value) => console.log("callbackify:", err, value));
}
main();
2.5
RangeError division by zero
callbackify: null 42
Synchronous functions
Many functions also have a blocking version whose name ends in Sync: fs.readFileSync, fs.existsSync, child_process.execSync. They return the result or throw. They're fine, and simpler, in command-line scripts and at startup, such as reading configuration before a server begins accepting connections. Inside a server's request handlers, they're a serious mistake: while one request waits on a Sync call, every other request waits too.
The event loop phases
Article 94 described the event loop in general terms: a queue of tasks plus a microtask queue. Node's loop, implemented by libuv, runs in phases, each with its own queue of callbacks:

- timers: callbacks of
setTimeoutandsetIntervalwhose time has come. - pending callbacks: a few system callbacks deferred from the previous iteration.
- poll: run I/O callbacks (file reads completed, data arrived on sockets). If nothing else is scheduled, the loop waits here for I/O.
- check:
setImmediatecallbacks. - close callbacks:
closeevents such assocket.on("close").
After each callback, in any phase, Node drains the microtask queues: first the process.nextTick queue, then promise reactions and queueMicrotask callbacks. Starting from inside an I/O callback, the order is fully predictable:
const fs = require("node:fs");
fs.stat(process.cwd(), () => { // we are now inside an I/O callback
console.log("1. I/O callback (poll phase)");
setTimeout(() => console.log("7. setTimeout 0 (timers phase, next loop iteration)"), 0);
setImmediate(() => console.log("6. setImmediate (check phase, this iteration)"));
Promise.resolve().then(() => console.log("4. promise reaction (microtask)"));
queueMicrotask(() => console.log("5. queueMicrotask (microtask)"));
process.nextTick(() => console.log("3. process.nextTick (before promise microtasks)"));
console.log("2. end of the I/O callback's synchronous code");
});
1. I/O callback (poll phase)
2. end of the I/O callback's synchronous code
3. process.nextTick (before promise microtasks)
4. promise reaction (microtask)
5. queueMicrotask (microtask)
6. setImmediate (check phase, this iteration)
7. setTimeout 0 (timers phase, next loop iteration)
From an I/O callback, the loop moves on to the check phase, so setImmediate runs before setTimeout(fn, 0), which must wait for the next timers phase. In the main script, outside any callback, the order of those two isn't guaranteed, because it depends on how quickly the loop starts. Don't write code that relies on it.
process.nextTick vs queueMicrotask
process.nextTick(fn) runs fn right after the current operation, normally even before promise microtasks (in ES modules, pending promise reactions can run first). Node's own internals use it, for example to emit an event after the constructor that created an emitter has returned. Because recursive nextTick calls run before any I/O, they can starve the event loop. For new code, queueMicrotask (standard and portable) or setImmediate (yields to I/O first) are usually better choices.
Blocking the loop
Every millisecond your JavaScript spends computing is a millisecond the loop can't handle anything else:
const start = Date.now();
setTimeout(() => {
const late = Date.now() - start;
console.log(`timer asked for 10 ms, ran after at least 90 ms: ${late >= 90}`);
}, 10);
// Synchronous CPU work: nothing else can run on this thread meanwhile
while (Date.now() - start < 100) { /* busy */ }
console.log("busy loop finished");
busy loop finished
timer asked for 10 ms, ran after at least 90 ms: true
In a server, the same effect delays every client. Common causes include large JSON.parse/JSON.stringify calls, regular expressions with catastrophic backtracking (article 82), synchronous file or crypto calls such as crypto.pbkdf2Sync, sorting huge arrays, and image or PDF processing. Remedies:
- Use the asynchronous API versions.
- Move CPU-heavy work to worker threads (article 131) or a separate service.
- Split long loops into chunks that yield between them (
await setImmediate()fromnode:timers/promises). - Measure it:
perf_hooks.monitorEventLoopDelay()reports how late the loop is running, a key health metric for Node services.
Common questions
Is Node really single-threaded?
Your JavaScript runs on one thread per process (or per worker). Node itself uses more threads: libuv's thread pool for files, DNS and crypto, plus V8's background threads for garbage collection and compilation.
Should I use fs.readFileSync or await readFile?
In a short script or during startup, readFileSync is simple and fine. Anywhere concurrency matters, such as request handlers or anything running while a server is up, use the promise version.
Why didn't my try/catch catch the error from fs.readFile?
The callback runs later, after the try block has finished. Errors from callback APIs arrive as the callback's first argument. With the promise API and await, try/catch works as expected.
Summary
- Node runs JavaScript on one thread and performs I/O without blocking: network through the OS, and files, DNS and some crypto through libuv's thread pool.
- APIs come as error-first callbacks, promises (
node:fs/promisesand similar, orutil.promisify), and blocking...Syncfunctions for scripts and startup code. - The event loop runs in phases: timers, pending callbacks, poll (I/O), check (
setImmediate) and close. After each callback,process.nextTickcallbacks run, then promise microtasks. - From an I/O callback,
setImmediatebeatssetTimeout(fn, 0); in the main script, their order isn't guaranteed. - CPU-heavy synchronous work blocks every pending callback. Move it off the main thread or split it up.
Practice Questions
What does this print when run as a CommonJS script (for example, a .cjs file)?
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
Answer
sync, tick, promise, immediate. Synchronous code runs first; then the nextTick queue, then promise microtasks; setImmediate waits for the check phase of the event loop.
In an ES module (.mjs), the output is sync, promise, tick, immediate: the module body itself runs as part of a promise job, so the promise queue is drained before Node gets to its nextTick queue. This is one more reason not to depend on the relative order of nextTick and promises.
Convert this callback API into an async function using promises.
fs.readFile("users.json", "utf8", (err, text) => {
if (err) return handle(err);
show(JSON.parse(text));
});
Answer
const { readFile } = require("node:fs/promises");
async function loadUsers() {
try {
show(JSON.parse(await readFile("users.json", "utf8")));
} catch (err) {
handle(err);
}
}
The try block now also catches JSON parse errors, which the callback version didn't handle.
A server endpoint hashes passwords with crypto.pbkdf2Sync, and all requests become slow under load. Why, and what's the fix?
Answer
pbkdf2Sync blocks the event loop for the whole hashing time, so every other request waits. Use the asynchronous crypto.pbkdf2 (or scrypt), which runs on the libuv thread pool and doesn't block the JavaScript thread.
Why can recursive process.nextTick calls freeze a server?
Answer
The nextTick queue is drained completely before the event loop continues. If each callback schedules another, the queue never empties, so timers and I/O callbacks never run.
Previous: Node.js Fundamentals: Running Programs, Arguments, Environment, Life Cycle and Modules
Next: Node Buffers: Binary Data, Encodings, Reading and Writing Bytes

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.