Performance: Callback pattern and callback hell
This concept affects page responsiveness and interaction speed by how asynchronous tasks are managed and how the event loop is utilized.
Jump into concepts and practice - no test required
import { readFile } from 'fs/promises'; async function readFiles() { try { const data1 = await readFile('file1.txt'); const data2 = await readFile('file2.txt'); const data3 = await readFile('file3.txt'); console.log(data1.toString(), data2.toString(), data3.toString()); } catch (err) { console.error(err); } } readFiles();
fs.readFile('file1.txt', (err, data1) => { if (err) throw err; fs.readFile('file2.txt', (err, data2) => { if (err) throw err; fs.readFile('file3.txt', (err, data3) => { if (err) throw err; console.log(data1.toString(), data2.toString(), data3.toString()); }); }); });
| Pattern | Event Loop Blocking | Code Complexity | Responsiveness Impact | Verdict |
|---|---|---|---|---|
| Nested callbacks (callback hell) | High - long blocking chains | High - hard to read and maintain | High - delays input processing | [X] Bad |
| Async/await with promises | Low - yields to event loop | Low - clean and readable | Low - fast input response | [OK] Good |
function first(callback) {
setTimeout(() => {
console.log('First');
callback();
}, 100);
}
function second() {
console.log('Second');
}
first(second);readFile('file1.txt', function(err, data1) {
if (err) throw err;
readFile('file2.txt', function(err, data2) {
if (err) throw err;
readFile('file3.txt', function(err, data3) {
if (err) throw err;
console.log(data1, data2, data3);
});
});
});