Lesson 31 / 38

Callbacks & Callback Hell

The original way to handle async work, and its downside.

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.