# Promises in JavaScript

Think of **Promise** in JavaScript like a promise made by a friend Bhai, I’ll bring the Samosas *for party.*

When your friend makes this promise, you dont have samosas yet but you have their word. You can continue planning the party based on that commitment.

## Callback Hell

Before Promises, we used **Callbacks**. Imagine trying to organize a massive Indian wedding where every vendor needs a phone call, and you can't start one task until the previous one is done.

```javascript
// Callback Hell: Hard to read and harder to debug
getGroom(function(groom) {
    getSherwani(groom, function(sherwani) {
        getTailor(sherwani, function(fittedSherwani) {
            getWedding(fittedSherwani, function() {
                console.log("Finally, Shaadi Mubarak!");
            });
        });
    });
});
```

This "Pyramid of Doom" makes code unreadable and messy. Promises were introduced to clean up this and make code look clean.

To know more about this problem : Read this [Callbacks in JavaScript](https://tech-blogs-shivanshu.hashnode.dev/callbacks-in-javascript#the-problem-callback-nesting-callback-hell)

## What is a Promise ?

A Promise is an object representing eventual completion (or failure) of asynchronous operation. Think of it like a **Zomato Order**

1.  **Pending:** Order is placed and you are waiting.
    
2.  **Resolved:** The delivery boy arrives with your food. A Success
    
3.  **Rejected:** The restaurant is closed or out of stock. The order is cancelled.
    

## Handling Success and Failure

In JavaScript we use `.then()` for when things go right and `.catch()` for when they go wrong.

```javascript
const bringSamosas = new Promise((resolve, reject) => {
    let shopOpen = true; 

    if (shopOpen) {
        resolve("Garma garam Samosas are here");
    } else {
        reject("Shop was closed, sorry yaara.");
    }
});

bringSamosas
    .then((message) => {
        console.log("Success: " + message); // Runs if resolved
    })
    .catch((error) => {
        console.log("Error: " + error); // Runs if rejected
    });
```

## Promise Chaining

One of the best features of Promises is **Chaining**. It allows you to perform a multiple asynchronous steps one after another.

Instead of nesting functions inside each other you chain them:

```javascript
bookTickets()
    .then((tickets) => {
        return buyPopcorn(tickets);
    })
    .then((snack) => {
        return watchMovie(snack);
    })
    .then(() => {
        console.log("What a great day!");
    })
    .catch((err) => {
        console.log("Plan cancelled: " + err); // Catches errors from ANY step above
    });
```

### Summary

Promises turn if then else into a clean flow. They allow JavaScript to handle heavy tasks like fetching data from a server or processing a payment without freezing screen, ensuring **Future Value** is handled whenever it arrives.

Thanks for Reading
