CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

index.js
// Define loadUser and call it with an error-first callback

Sample solution

index.js
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);
});

Expected output

Ayşe

Practice 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); }); }).

Starter code

index.js
// Define loadUser and loadPosts, call them nested

Sample solution

index.js
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);
  });
});

Expected output

Ayşe: 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the concepts

Term Meaning
cb() Callback invocation
makeAdder Higher-order function
forEach Method using a callback
(err, data) Error-first signature
pyramid indent Callback hell symptom

2 How is a file reader built?

  • With a single function
  • Only with console.log
  • With chained callbacks Correct answer
  • With array methods

Explanation: chained callbacks let each step call the next.

3 Error-first signature

Question
function handler(____, data) { if (err) throw err; console.log(data); }
Answer
function handler(err, data) { if (err) throw err; console.log(data); }

Explanation: the first parameter is err; this is the Node.js convention.

All lessons in Beginner