Summary - Callbacks
Build a file-read simulation using an error-first callback.
Summary - Callbacks
In this group you learned the foundations of callbacks. A callback is a function you pass as an argument to another function. Asynchronous callbacks are invoked later by the event loop. In Node.js, the error-first convention makes the first parameter the error. Nested callbacks create callback hell; you fix it by splitting into named functions.
Now you will write two tasks that bring it all together: a file-read simulation using an error-first callback, and a sequence of timers split into named functions.
Exercise Write a readFile simulation
Define a function named readFile. It should take two parameters: filename and callback. Inside the function, use setTimeout to check for an error after 100 ms. If filename is 'missing.txt', call callback with new Error(...). Otherwise, call callback with null and a content string.
Show example solution
function readFile(filename, callback) {
setTimeout(() => {
if (filename === 'missing.txt') {
callback(new Error('File missing'));
} else {
callback(null, 'File content');
}
}, 100);
}
Exercise A sequential flow with named functions
Define two named functions: loadData and showData. loadData should take a callback parameter and use setTimeout to call callback with a data string after 100 ms. showData should take a data parameter and log it with console.log. Finally, call loadData(showData).
Show example solution
function loadData(callback) {
setTimeout(() => {
callback('Data loaded');
}, 100);
}
function showData(data) {
console.log(data);
}
loadData(showData);
Test yourself
-
If there is no error in an error-first callback, what is the first parameter?
- undefined
- null
- false
- An empty string
Show answer
null — Correct! When there is no error, the first parameter is null; the result is the second parameter.
-
Match the concepts
- callback
- Called-back function
- event loop
- Runs async callback
- err parameter
- First argument
- named function
- Callback hell fix