DEV Community

Bala Murugan
Bala Murugan

Posted on

Why Promises Are Better Than Callbacks

What is a Callback:

    A callback is a function that is passed as an argument to another function and executed later.
Enter fullscreen mode Exit fullscreen mode

Example:

function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

function sayBye() {
  console.log("Bye!");
}

greet("Bala", sayBye);

Output:

Hello Bala
Bye!
Enter fullscreen mode Exit fullscreen mode

What is Callback Hell:

When callbacks are nested inside other callbacks many times, it becomes hard to read and maintain. This is called Callback Hell.

Example:

setTimeout(() => {
  console.log("Step 1");

  setTimeout(() => {
    console.log("Step 2");

    setTimeout(() => {
      console.log("Step 3");

      setTimeout(() => {
        console.log("Step 4");
      }, 1000);

    }, 1000);

  }, 1000);

}, 1000);
Enter fullscreen mode Exit fullscreen mode

This code looks like a pyramid shape.
This is called Callback Hell or Pyramid of Doom.

Problems in Callback Hell:
*Hard to read
*Hard to debug
*Hard to maintain
*Error handling is difficult

What is a Promise:

A Promise is used to handle asynchronous operations in a better way.
Enter fullscreen mode Exit fullscreen mode

A Promise has 3 states:

Pending
Resolved (Success)
Rejected (Error)

Promise Example:

let promise = new Promise(function(resolve, reject) {
  let success = true;

  if (success) {
    resolve("Task completed");
  } else {
    reject("Task failed");
  }
});

promise
  .then(function(result) {
    console.log(result);
  })
  .catch(function(error) {
    console.log(error);
  });

Enter fullscreen mode Exit fullscreen mode

Callback Hell vs Promise:

Callback Hell Promise
Nested callbacks Chain using .then()
Hard to read Easy to read
Hard to maintain Easy to maintain
Error handling difficult Error handling easy with .catch()

Promise States Diagram:

Draw a simple flow:

         [Pending]
       /   \
      /     \
Enter fullscreen mode Exit fullscreen mode

[Resolved] Rejected (Error)

              Real-World Example Diagram:

Use a food order example
Enter fullscreen mode Exit fullscreen mode

CallbackHell:

Order Food

Prepare Food

Pack Food

Deliver Food

Promise:

Order → Prepare → Pack → Deliver

You can end your blog like this:

",Callback Hell makes code messy. Promises make code clean, readable, and easy to manage."
Enter fullscreen mode Exit fullscreen mode

Top comments (0)