Performance: Events vs callbacks decision
MEDIUM IMPACT
This concept affects how asynchronous operations impact responsiveness and CPU usage in Node.js applications.
const EventEmitter = require('events'); class DataFetcher extends EventEmitter { fetch() { database.query('SELECT * FROM table', (err, result) => { if (err) return this.emit('error', err); this.emit('data', result); }); } } const fetcher = new DataFetcher(); fetcher.on('data', (result) => { processData(result, (err, processed) => { if (err) return fetcher.emit('error', err); fetcher.emit('done', processed); }); });
function fetchData(callback) {
database.query('SELECT * FROM table', (err, result) => {
if (err) return callback(err);
processData(result, (err, processed) => {
if (err) return callback(err);
callback(null, processed);
});
});
}| Pattern | Callback Nesting | Event Loop Blocking | Code Complexity | Verdict |
|---|---|---|---|---|
| Callbacks with nesting | High (deep nesting) | Medium (blocking during callbacks) | High (hard to maintain) | [X] Bad |
| Event-driven with emitters | Low (flat event handlers) | Low (non-blocking event dispatch) | Low (clear separation) | [OK] Good |