Callback Hell and Promises
Tags: javascript, programming, beginners, codenewbie
Published: 2023-04-03 19:02:28

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gc8fna4lylixczsill3l.png)

_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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z52zdyiqmfesx63ggc8s.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chjtb7l3lptzundml1in.jpeg)

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);
});
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdt568rjsehc3qzicb3g.png)
_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);
});
```

#####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);
        }
   });


```
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!