Node.js
Summary - Callbacks
Combine higher-order, error-first and callback hell to write a file reader.
Summary - Callbacks
In this group you saw five aspects of callbacks: the basic callback concept, higher-order functions, using callbacks with forEach, Node.js's error-first convention, and the callback hell trap.
You can combine these to build a real flow. A file reader, for example: load the user, check the error, then load the posts. Each step takes a callback and follows the error-first convention.
In the final task you will write a chained loader. You will pass the data from the first callback to the second call and check the error at each step. This pattern sums up the classic callback-based flows of Node.js.
Exercise File reader simulation
Define a function loadUser(id, cb): if id is 0, call cb(new Error('missing'), null); otherwise call cb(null, { name: 'Ayşe' }). Call it as loadUser(1, (err, user) => { if (err) { console.error(err.message); return; } console.log(user.name); }) so the name prints in the no-error case.
Show example solution
function loadUser(id, cb) {
if (id === 0) { cb(new Error('missing'), null); return; }
cb(null, { name: 'Ayşe' });
}
loadUser(1, (err, user) => {
if (err) { console.error(err.message); return; }
console.log(user.name);
});
Exercise Chained loader
Define a function loadUser(id, cb) that calls cb(null, { name: 'Ayşe' }). Define loadPosts(user, cb) that calls cb(null, ['a', 'b', 'c']). Call them nested as loadUser(1, (err, user) => { loadPosts(user, (err2, posts) => { console.log(user.name + ': ' + posts.length); }); }).
Show example solution
function loadUser(id, cb) {
cb(null, { name: 'Ayşe' });
}
function loadPosts(user, cb) {
cb(null, ['a', 'b', 'c']);
}
loadUser(1, (err, user) => {
loadPosts(user, (err2, posts) => {
console.log(user.name + ': ' + posts.length);
});
});
Test yourself
-
Match the concepts
- cb()
- Callback invocation
- makeAdder
- Higher-order function
- forEach
- Method using a callback
- (err, data)
- Error-first signature
- pyramid indent
- Callback hell symptom
-
How is a file reader built?
- With a single function
- Only with console.log
- With chained callbacks
- With array methods
Show answer
With chained callbacks — chained callbacks let each step call the next.
-
Error-first signature
function handler(____, data) { if (err) throw err; console.log(data); }
Show answer
function handler(err, data) { if (err) throw err; console.log(data); }
Next lesson: Task model