DEV Community

Cover image for Callback Hell and Promises
Md Anas Sabah
Md Anas Sabah

Posted on

Callback Hell and Promises

For understanding the concept of Callback Hell, I think you should know about Callback.

What is Callback?
Callback is a powerful way to do asynchronous thing in JavaScript. It is a function which is to be executed after another function has finished execution.

Suppose, we have an E-commerce Application where we have createOrder and proceedToPayment function which have to execute one after another respectively.
We have dependency between those two , We can manage those dependency in our code using callback because it's an async operation.

callback

When JavaScript Engine executes this code it will just call the createOrder api.
Now it is responsibility of createOrder function to callback proceedToPayment api

Issues with Callback

1. Inversion of Control
2. Callback Hell

Inversion of Control

Inversion of control is like you loose the control of code when you are using callback.

Callback Hell

callback hell

You are seeing now a nesting of functions here and code also looks scary and this is what we called Callback Hell. For a big application it creates more nesting.

CallBack hell1

To avoid this, we will see now Promises.

Promises

To fix the issue of Inversion of Control and Callback Hell, ES6(ECMAScript 6) Promise is the easier way to work with asynchronous programming in JavaScript.
A promise acts as a container for a future value.

For Example: const promise = createOrder(cart)
Whenever JavaScript engine executes this line, this createOrder api will return us a promise.(Promise is nothing but an empty object) and program will just go on and execute.
But after fetching data from API, promise object get filled automatically.

Now how will we attach our callback to that promise?

We will use .then method.

promise.then(function(orderID){
        proceedToPayment(orderID);
});
Enter fullscreen mode Exit fullscreen mode

This callback function runs automatically after fetching data from api in the promise object.

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

There are three states of promise:
1.pending
2.fulfilled
3.rejected

Promise Chaining

Taking example of callback hell we can also do promise chaining

promise-chaining
We always return a promise from a promise, when we are chaining it

Create a Promise

Consumer Part
const cart = ["shoes", "pants","kurta"];
const promise = createOrder(cart);
promise.then(function(orderID){
        proceedToPayment(orderID);
});
Enter fullscreen mode Exit fullscreen mode
Producer Part:
function createOrder(cart){
   const pr = new Promise(function(resolve,reject){
       //create order
       //validate cart
       //orderID
      if(!validateCart(cart){
            const err = new Error("cart is not valid")
            reject(err);
         }
      const orderID= "1234"
      if(orderID){
         setTimeOut(function(){
              resolve(orderID);
             },5000);
        }
   });


Enter fullscreen mode Exit fullscreen mode

Thanks for reading this long post! I hope it helped you understand these topics a little better. If you liked this post, then please do give me a few ❤️ and share it if you can. You are welcome to
give any suggestions in comments and ask anything!

Top comments (0)