# Promise in Javascript

The `Promise` object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

***In simple words :***

* A Promise is like a guarantee that something will be done in the future. It handles tasks that takes time, like loading data from the website. Once the task is done, the Promise either gives you the result (success) or an error (failure)
    

## Promise States

1. Pending → The task is still in progress.
    
2. Fulfilled (Resolved) → The task is completed successfully.
    
3. Rejected → The task is failed with an error.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739875916784/5cee3efa-ab48-4f13-951a-af76a2f363e8.png align="center")

## Handling a Promise

To handle the result of the promise, you can use:

* `.then()` to handle success (when the Promise is Resolved)
    
* `.catch()` to handle errors (when the Promise is Rejected)
    
* `.finally()` to execute the code after the Promise finishes, regardless of success or failure.
    

### Example

```javascript
const myPromise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("Task completed successfully!");
  } else {
    reject("Task failed !!!");
  }
});

myPromise
  .then(result => {
    console.log(result); // Runs if resolved
  })
  .catch(error => {
    console.error(error); // Runs if rejected
  })
  .finally(() => {
    console.log("Promise has finished."); // Runs after the .then() or .catch()
  });
```

## Understanding Thenable objects

Promises are thenable objects, meaning they can be chained with `.then()` to handle asynchronous operations.

### Example (with fetch() method.):

```javascript
fetch('https://api.github.com/users/AkLuffy07')
.then(response => {
    return response.json();
})
.then(data => {
    console.log("GitHub Data :: ", data);
})
.catch(err => console.log(err))
.finally(() => console.log("Fetch method is completed.."))
```

In the above example, **fetch** method returns the Promise.

* So in `.then()` return the response in the json format.
    
* And in the next `.then()` log the response data. (In the second `.then()` response is fetched from the first `.then()` return.)
    

<mark>For more details on the Fetch API, you can refer to this article</mark>: [Fetch API](https://java-script.hashnode.dev/fetch-api)

## Conclusion

* Promises manages asynchronous operations efficiently.
    
* `.then()` handles the success, `.catch()` handles the errors, `.finally()` handles cleanup.
    
* Understanding **thenables** and their chaining is crucial for modern JavaScript development.
