Lesson 32 / 40

Callbacks & Callback Hell

Handle asynchronous work with callbacks and see why nesting them leads to callback hell.

What is a callback

A callback is a function passed into another function, to be run once some work finishes.

function fetchData(callback) {
  setTimeout(() => callback("data loaded"), 1000);
}
fetchData((result) => console.log(result));

Callback hell

Nesting async steps inside each other's callbacks quickly forms a hard-to-read pyramid.

getUser(1, (user) => {
  getPosts(user.id, (posts) => {
    getComments(posts[0].id, (comments) => {
      console.log(comments);
    });
  });
});

Why it's a problem

Deeply nested callbacks are hard to read and to handle errors in — this pyramid shape is exactly what Promises were built to fix.