Sub topic 11
Trusting Callbacks: Inversion of Control and Consistent Async Behavior
This chapter assumes you know how asynchronous callbacks work, how the event loop orders tasks and microtasks, and how the error-first convention works in Node.js. Those topics are covered in earlier chapters.
What Inversion of Control Means
When you pass a callback to a function, you also give up control over how it gets called. The receiving function decides:
- whether your callback runs at all
- how many times it runs
- whether it runs now (synchronously) or later (asynchronously)
- which arguments it receives, and whether errors are reported or swallowed
This is called inversion of control. Your code no longer drives the next step. The other function drives it. With a well-tested API such as fs.readFile, this is fine. With your own helpers or a third-party library, any of these decisions can be wrong.
Bug 1: Sometimes Sync, Sometimes Async
A common mistake is a function that calls its callback synchronously on one path and asynchronously on another. A cache is the usual example:
const cache = new Map();
function getValueBad(key, callback) {
if (cache.has(key)) {
callback(null, cache.get(key)); // runs immediately
return;
}
setTimeout(() => {
cache.set(key, key.toUpperCase());
callback(null, cache.get(key)); // runs later
}, 10);
}
function demo(label) {
let ready = false;
getValueBad('a', (err, value) => {
console.log(label, 'ready =', ready, 'value =', value);
});
ready = true;
}
demo('first'); // first ready = true value = A
setTimeout(() => demo('second'), 50); // second ready = false value = AThe same call site behaves differently depending on cache state. On a miss, the code after the call (ready = true) runs first. On a hit, the callback runs first. Bugs like this depend on timing, which makes them hard to reproduce. Node.js developers call this "releasing Zalgo."
The Fix: Always Be Asynchronous
Defer the cached result so every path calls back asynchronously. queueMicrotask (or process.nextTick in Node.js) does this with almost no delay:
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);
}
getValue('a', slowLoad, (err, v) => console.log('miss:', v));
setTimeout(() => {
getValue('a', slowLoad, (err, v) => console.log('hit:', v));
console.log('after hit call'); // always logs before "hit: A"
}, 50);Now the code after the call always runs before the callback, whether the cache hits or misses.
Bug 2: Called Too Many Times
A buggy helper can call your callback twice. This often happens when the error path forgets to return:
function parseJson(text, callback) {
try {
const data = JSON.parse(text);
callback(null, data);
} catch (err) {
callback(err);
}
}
parseJson('{"a":1}', (err, data) => {
console.log('callback', err ? 'error' : 'ok');
throw new Error('bug in my handler');
});The handler throws inside the try block, so catch runs and calls the callback a second time with the handler's own error. You can protect yourself with a once wrapper:
function once(callback) {
let called = false;
return function (...args) {
if (called) {
console.warn('callback invoked more than once; ignoring');
return;
}
called = true;
return callback(...args);
};
}
function flaky(callback) {
callback(null, 'first');
callback(null, 'second'); // bug in the library
}
flaky(once((err, value) => console.log('got', value)));
// got first
// callback invoked more than once; ignoringThe fix inside parseJson itself is to call the callback outside the try block, so errors thrown by the handler never reach catch.
Other Trust Problems
| Problem | Symptom | Defense |
|---|---|---|
| Called sync and async | Order changes between calls | Always defer with `queueMicrotask` or `process.nextTick` |
| Called more than once | Duplicate work, double responses | `once` wrapper, or `return` after each callback call |
| Never called | Operation hangs silently | Timeout wrapper that calls back with an error |
| Errors swallowed | Failures disappear | Always pass errors as the first argument |
Promises, covered in the next chapter, enforce these guarantees for you: a Promise settles at most once, and its reactions always run asynchronously as microtasks.
Exercise
A function lookup(id, cb) calls cb synchronously when id is in a local Map and calls it from a network response otherwise. A caller writes lookup(id, cb); started = true; and reads started inside cb. What value of started does the callback see on each path, and how do you fix lookup?
Show answer
On a cache hit the callback runs before started = true, so it sees false. On a network path it runs later and sees true. Fix it by deferring the cache-hit path, for example queueMicrotask(() => cb(null, map.get(id))), so the callback always runs after the calling code finishes and always sees true.
Exercise
Write a withTimeout(fn, ms) wrapper that returns a function taking a callback. It calls fn(callback) but makes sure the callback runs exactly once: with new Error('timeout') if ms passes first, or with fn's result otherwise.
Show answer
function withTimeout(fn, ms) { return function (callback) { let done = false; const timer = setTimeout(() => { if (done) return; done = true; callback(new Error('timeout')); }, ms); fn((...args) => { if (done) return; done = true; clearTimeout(timer); callback(...args); }); }; }