Course contentsShow
← JavaScript
Lesson 1249 of 2,72328. CallbacksFree lesson

Callback Hell Example: API Chains

Making dependent API requests with callbacks creating a pyramid structure.

Callback Hell Example: API Chains

You'll learn how chaining multiple dependent API requests with callbacks creates the infamous "pyramid of doom."

The Chain Reaction Problem

When you need to make API calls where each request depends on the previous one's result, callbacks force you into a nested structure. Imagine fetching a user's profile, then their posts, then comments on the first post, then the author of the first comment—each step must wait for the last.

The Pyramid Structure

// Get user data, then their posts, then post comments
getUserData(userId, function(err, user) {
  if (err) {
    console.error('User fetch failed:', err);
    return;
  }
  
  getUserPosts(user.id, function(err, posts) {
    if (err) {
      console.error('Posts fetch failed:', err);
      return;
    }
    
    getPostComments(posts[0].id, function(err, comments) {
      if (err) {
        console.error('Comments fetch failed:', err);
        return;
      }
      
      getCommentAuthor(comments[0].authorId, function(err, author) {
        if (err) {
          console.error('Author fetch failed:', err);
          return;
        }
        
        console.log('Final author:', author.name);
        // Finally! But look at this indentation...
      });
    });
  });
});

Why It's Problematic

Each API call requires the previous one's data, forcing deeper nesting. Error handling must repeat at every level. The code drifts rightward, becoming harder to read and maintain. You lose the natural top-to-bottom flow of sequential operations.

Key Takeaway: Chaining dependent API requests with callbacks creates deeply nested, hard-to-maintain code where each request pushes you further right—a classic example of callback hell that screams for better alternatives like Promises or async/await.