0Pricing
Frontend Academy · Lesson

Callbacks and Callback Hell

Understand callback-based async, identify the nesting problem known as callback hell, and see why Promises were introduced to solve it.

What Are Callbacks?

A callback is a function passed as an argument to another function, to be called later when some work is complete. Callbacks are the original JavaScript async pattern — they predate Promises.

// Synchronous callback:
[1, 2, 3].forEach(function(n) {
  console.log(n);
});

// Async callback:
setTimeout(function() {
  console.log('1 second later');
}, 1000);

Node.js Error-First Callbacks

Node.js standardised a convention: callbacks receive an error as the first argument and the result as the second. If err is null/undefined, the operation succeeded.

fs.readFile('data.json', 'utf8', function(err, data) {
  if (err) {
    console.error('Failed to read file:', err);
    return;
  }
  console.log('File contents:', data);
});

All lessons in this course

  1. The Event Loop: Call Stack Queue Microtasks
  2. Callbacks and Callback Hell
  3. Promises: then catch finally Promise.all
  4. async/await and Error Handling
← Back to Frontend Academy