Sub topic 3
Event Listeners, Callback Hell, and Promisification
This chapter assumes you know error-first callbacks, the event loop, and how to run scripts with Node.js.
Event Listeners: Callbacks That Fire Many Times
A callback passed to fs.readFile runs once. An event listener runs every time its event fires. To remove a listener, you must pass the same function reference you registered, so give the listener a name instead of writing it inline.
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
function onTick(n) {
console.log('tick', n);
}
emitter.on('tick', onTick);
emitter.emit('tick', 1); // tick 1
emitter.off('tick', onTick);
emitter.emit('tick', 2); // nothing is loggedCallback Hell and How to Flatten It
Each step that depends on an earlier one adds another level of nesting, and the code drifts to the right. To flatten it, move each step into a named function and use early returns on errors. Wrap synchronous code that can throw, such as JSON.parse, so its errors reach the callback.
const fs = require('node:fs');
function readConfig(path, callback) {
fs.readFile(path, 'utf8', (err, text) => {
if (err) return callback(err);
let config;
try {
config = JSON.parse(text);
} catch (parseErr) {
return callback(parseErr);
}
callback(null, config);
});
}
function handleConfig(err, config) {
if (err) return console.error(err.message);
console.log('Loaded keys:', Object.keys(config));
}
readConfig('config.json', handleConfig);Trusting Callbacks: Inversion of Control
When you pass a callback, you give up control over when it runs and how often. You trust the other code to call it exactly once and always asynchronously. If a function calls back synchronously on one path and asynchronously on another, its callers see a different order of execution depending on which path ran. Use queueMicrotask so the callback runs asynchronously on every path:
const cache = new Map();
function getValue(key, loadFn, callback) {
if (cache.has(key)) {
queueMicrotask(() => callback(null, cache.get(key)));
return;
}
loadFn(key, (err, value) => {
if (err) return callback(err);
cache.set(key, value);
callback(null, value);
});
}From Callbacks to Promises and async/await
A Promise settles only once, so it fixes the problem of a callback being called more than once. util.promisify converts any error-first function into one that returns a Promise:
const util = require('node:util');
const fs = require('node:fs');
const readFile = util.promisify(fs.readFile);
async function main() {
const text = await readFile('config.json', 'utf8');
console.log('Read', text.length, 'characters');
}
main().catch((err) => console.error(err.message));For APIs that are not error-first, wrap them by hand. The Promise still uses a callback underneath:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
delay(500).then(() => console.log('half a second later'));Exercise
Why does emitter.off('tick', (n) => console.log('tick', n)) fail to remove a listener that was registered with identical inline code?
Show answer
Each arrow function expression creates a new function object. off compares function references, and the new function is a different reference from the one that was registered, so nothing is removed. Store the listener in a named variable and pass that variable to both on and off.
Exercise
Why does getValue use queueMicrotask on a cache hit instead of calling callback directly?
Show answer
Calling callback directly would make cache hits synchronous while cache misses stay asynchronous. Callers would then see code run in a different order depending on the cache state. Deferring the call keeps the callback asynchronous on every path.