Performance: Error-first callback convention
This pattern affects how asynchronous operations handle errors and results, impacting responsiveness and error handling flow in Node.js applications.
Jump into concepts and practice - no test required
fs.readFile('file.txt', (err, data) => { if (err) { console.error('Error:', err); return; } console.log(data.toString()); });
fs.readFile('file.txt', (data) => { if (!data) { console.log('Error occurred'); return; } console.log(data.toString()); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Error-first callback | N/A (Node.js backend) | N/A | N/A | [OK] Good |
| Non-error-first callback | N/A | N/A | N/A | [X] Bad |
function readFile(callback) {
setTimeout(() => {
callback(null, 'file content');
}, 100);
}
readFile((err, data) => {
if (err) {
console.log('Error:', err);
} else {
console.log('Data:', data);
}
});function getData(callback) {
const error = null;
const result = 'Success';
callback(result, error);
}
getData((err, data) => {
if (err) {
console.log('Error:', err);
} else {
console.log('Data:', data);
}
});function fetchUser(id, callback) {
if (id <= 0) {
callback(new Error('Invalid ID'), null);
} else {
setTimeout(() => {
callback(null, { id, name: 'Alice' });
}, 50);
}
}fetchUser to correctly handle errors and print the user's name or the error message?