Sub topic 11
Trusting Callbacks: Inversion of Control and Consistent Async Behavior
This chapter assumes you know how asynchronous callbacks run, how the event loop orders tasks and microtasks, and how the Node.js error-first convention works. All of those were covered in earlier chapters. Here the question is a different one. When you pass a callback to code you did not write, what does that code promise to do with it, and what can you do when it breaks that promise?
What Inversion of Control Means
In ordinary code, your program decides what runs next. You call a function, it returns, and you carry on. With a callback, you give up that decision. You hand a function to someone else's code and trust it to call your function:
- exactly once,
- with the right arguments,
- at a predictable time,
- and to report errors instead of hiding them.
This handoff is called inversion of control. The rest of your program now depends on behavior that lives inside another module. Usually that module is well behaved. When it is not, the bugs are hard to trace, because the stack trace starts inside the library and your code only shows up as the victim.
The Ways a Callback Contract Breaks
| Failure | What you see | Typical cause |
|---|---|---|
| Sometimes sync, sometimes async | Code after the call sees different state on different runs | A cache or validation shortcut that calls back immediately |
| Never called | Request hangs, no error, no log | A code path that returns without calling back |
| Called more than once | Duplicate writes, "headers already sent" errors, double charges | A `try/catch` that also catches errors thrown by the callback |
| Called too early | Callback runs before setup code finishes | Same as the sync case |
| Error swallowed | Silent wrong results | An empty `catch` or an ignored `err` argument |
The rest of the chapter takes these on one at a time. Each fix can be applied in a library you control, and you can also use the same fix as a defensive wrapper around a library you do not control.
Inconsistent Timing: Releasing Zalgo
The most subtle failure is a function that calls its callback synchronously on some paths and asynchronously on others. The Node.js community calls this "releasing Zalgo," after a 2013 blog post by Isaac Schlueter. The problem is that the caller cannot know whether the code after the call runs before or after the callback.
const cache = new Map();
function getUserUnsafe(id, callback) {
if (cache.has(id)) {
callback(null, cache.get(id)); // synchronous on a cache hit
return;
}
setTimeout(() => {
const user = { id, name: `user-${id}` };
cache.set(id, user);
callback(null, user); // asynchronous on a cache miss
}, 10);
}
function load(id) {
let ready = false;
getUserUnsafe(id, (err, user) => {
console.log(`load ${user.name}: ready is ${ready}`);
});
ready = true;
}
load(1); // load user-1: ready is true
setTimeout(() => load(1), 50); // load user-1: ready is falseThe two calls to load(1) look the same, but they behave differently. The first call misses the cache, so the callback runs later and sees ready === true. The second call hits the cache, so the callback runs immediately, before ready = true executes. Any code that sets up state after starting the operation, such as registering a listener, starting a spinner, or assigning a variable, will break only when the cache is warm. Bugs like this often show up in production and not in tests, because test caches usually start cold.
The Fix: Always Defer
The rule is simple. If a function is ever asynchronous, make it always asynchronous. On the fast path, defer the callback instead of calling it directly:
const cache = new Map();
function getValue(key, loadFn, callback) {
if (cache.has(key)) {
// Stay asynchronous even on a cache hit
queueMicrotask(() => callback(null, cache.get(key)));
return;
}
loadFn(key, (err, value) => {
if (err) return callback(err);
cache.set(key, value);
callback(null, value);
});
}
function slowLoad(key, cb) {
setTimeout(() => cb(null, key.toUpperCase()), 10);
}
let ready = false;
getValue('a', slowLoad, () => {
getValue('a', slowLoad, (err, v) => console.log('hit:', v, 'ready:', ready));
ready = true;
});
// hit: A ready: trueThe cache hit still costs almost nothing, because a microtask runs as soon as the current synchronous code finishes. What the caller gains is a guarantee: the code after the call always runs first.
The same rule applies to argument validation. If a function would report a bad argument through its callback, defer that report too, or throw synchronously. Do not call the callback with an error right away while the success path stays asynchronous.
Choosing a Deferral Mechanism
| Mechanism | Runs | Environment | Notes |
|---|---|---|---|
| `queueMicrotask(fn)` | After current sync code, before the next task | Browsers and Node.js | Standard choice for "always async" |
| `process.nextTick(fn)` | Before Promise microtasks | Node.js only | Common in older Node code; the Node docs suggest `queueMicrotask` for most new code |
| `setImmediate(fn)` | In the check phase, after I/O callbacks | Node.js only | Lets pending I/O run first |
| `setTimeout(fn, 0)` | As a later task, often with a minimum delay | Browsers and Node.js | Slowest; browsers clamp nested timers to about 4 ms |
Called More Than Once
A callback that runs twice is often caused by a try/catch placed around too much code:
function parseLater(text, callback) {
setTimeout(() => {
try {
const value = JSON.parse(text);
callback(null, value); // if the callback throws...
} catch (err) {
callback(err); // ...it is called a second time
}
}, 0);
}
parseLater('{"ok":true}', (err, value) => {
console.log('called with', err ? 'error' : value);
if (!err) throw new Error('bug in caller');
});
// called with { ok: true }
// called with errorThe library meant the catch to handle parse failures. It also caught an exception thrown by the caller's own code and reported it back to the caller as if the parse had failed. The fix is to keep only the risky operation inside try and call the callback outside it. This is the pattern readConfig used in the error-first chapter:
function parseLaterSafe(text, callback) {
setTimeout(() => {
let value;
try {
value = JSON.parse(text);
} catch (err) {
return callback(err);
}
callback(null, value);
}, 0);
}If the caller's callback throws now, the exception propagates as an uncaught error. That is correct, because the bug is in the caller and should surface there.
A `once` Guard
When you cannot fix the library, wrap your callback so that only the first call has any effect:
function once(callback) {
let called = false;
return function (...args) {
if (called) {
console.warn('callback invoked more than once; ignoring');
return;
}
called = true;
return callback.apply(this, args);
};
}
function buggyLibrary(callback) {
setTimeout(() => {
callback(null, 'first');
callback(null, 'second'); // library bug
}, 0);
}
buggyLibrary(once((err, result) => console.log('got', result)));
// got first
// callback invoked more than once; ignoringLog the extra call; do not drop it silently. A second invocation means something upstream is wrong, and the warning tells you where to look.
Never Called
A callback that never runs is the hardest failure to notice, because nothing happens at all. The usual cause is a code path that returns early and forgets to call back:
function findUser(id, callback) {
if (id < 0) return; // bug: caller waits forever
setTimeout(() => callback(null, { id }), 10);
}The defense is a timeout that turns "nothing happened" into an error you can handle. Combine it with once, so that a late real response arriving after the timeout is ignored:
function once(callback) {
let called = false;
return function (...args) {
if (called) return;
called = true;
return callback.apply(this, args);
};
}
function withTimeout(ms, callback) {
const guarded = once(callback);
const timer = setTimeout(() => {
guarded(new Error(`Callback not called within ${ms} ms`));
}, ms);
return function (...args) {
clearTimeout(timer);
guarded.apply(this, args);
};
}
function findUser(id, callback) {
if (id < 0) return; // bug: never calls back
setTimeout(() => callback(null, { id }), 10);
}
findUser(-1, withTimeout(100, (err, user) => {
if (err) return console.error(err.message);
console.log('found', user);
}));
// Callback not called within 100 msWrong Arguments and Swallowed Errors
Wrapping cannot fix a library that passes the wrong data, but you can stop bad data from spreading. At the boundary where third-party results enter your code, check the shape you depend on:
function expectUser(callback) {
return function (err, user) {
if (err) return callback(err);
if (!user || typeof user.id !== 'number') {
return callback(new TypeError('Expected a user object with numeric id'));
}
callback(null, user);
};
}Swallowed errors are worse, because the library never tells you anything went wrong. The only fix is upstream: find the empty catch or the ignored err, and report a bug. In your own callbacks, never ignore the first argument. If you really have nothing to do with an error, log it.
Putting the Guards Together
The guards compose. Here is a single wrapper for calling an untrusted callback API. It makes the callback always asynchronous, runs it at most once, and gives up after a deadline:
function callSafely(fn, args, ms, callback) {
let done = false;
const finish = (err, result) => {
if (done) return;
done = true;
clearTimeout(timer);
// Always deliver asynchronously, even if fn called back synchronously
queueMicrotask(() => callback(err, result));
};
const timer = setTimeout(
() => finish(new Error(`Timed out after ${ms} ms`)),
ms
);
try {
fn(...args, finish);
} catch (err) {
finish(err); // fn threw synchronously instead of calling back
}
}
function syncSometimes(x, cb) {
if (x === 0) return cb(null, 'instant');
setTimeout(() => cb(null, 'later'), 5);
}
let after = false;
callSafely(syncSometimes, [0], 1000, (err, r) => {
console.log(r, 'after =', after); // instant after = true
});
after = true;In this wrapper the try/catch is safe, because it surrounds the library call and not your callback. Your callback always runs later in a microtask, outside the try block.
When to Guard and When to Fix
| Situation | Approach |
|---|---|
| You own the API | Fix it: always defer, call back exactly once, keep `try` narrow |
| Well-maintained library with a documented contract | Trust it, and validate result shapes at the boundary |
| Unmaintained or poorly tested library | Wrap with `once`, a timeout, and deferral |
| Many call sites using the same API | Write one wrapper, or convert the API to a Promise |
The last row points ahead. Promises were designed to provide these guarantees by default. A Promise settles only once, its reactions always run asynchronously, and a thrown error becomes a rejection instead of a second callback. The next chapter shows how to convert callback APIs to Promises so you get these guarantees without writing your own guard code.
Exercise
A function getConfig(callback) returns a cached object by calling callback(null, cached) directly, but reads from disk with fs.readFile on a cache miss. A caller writes let handled = false; getConfig(() => { console.log(handled); }); handled = true;. What does it log on a cold cache and on a warm cache, and how do you make both cases log the same value?
Show answer
On a cold cache it logs true, because the callback runs after the disk read, by which time handled = true has already executed. On a warm cache it logs false, because the callback runs synchronously before that line. To fix it, defer the cache-hit path with queueMicrotask(() => callback(null, cached)) (or process.nextTick in Node.js). Both cases then log true.
Exercise
Why does this code call cb twice when cb itself throws, and how do you rewrite it? fs.readFile(p, 'utf8', (err, t) => { if (err) return cb(err); try { cb(null, JSON.parse(t)); } catch (e) { cb(e); } });
Show answer
The try block contains both JSON.parse and the call to cb, so an exception thrown inside cb is caught and passed back to cb as an error. To fix it, parse inside the try into a variable, return cb(e) from the catch, and call cb(null, value) after the try/catch so that exceptions from cb are not caught.
Exercise
You wrap a callback with a 200 ms timeout guard. The real response arrives at 350 ms. What should happen to it, and which part of the wrapper ensures that?
Show answer
The caller should already have received a timeout error at 200 ms, so the late response must be ignored. The once guard (the done or called flag) ensures this by dropping every invocation after the first. The underlying operation may still have completed, so the caller should treat a timeout as "outcome unknown" rather than "failed."