Introduction to Promises in JavaScript.
Tags: beginners, javascript, webdev, tutorial
Published: 2021-05-28 13:46:15

I promise that you will have a good understanding of promises by the end of the article 😁.

## What is a Promise

A promise in javascript is just like a promise we make in our lives. It refers to an event that will occur in the future.
Promises in javascript are used to handle asynchronous operations. Promises have three possible states -

1. Pending (Initial State)
2. Fulfilled (Successful)
3. Rejected (Failed)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gokowel8p73wuh407x87.png)

When we make a promise, its state will be pending till either it is fulfilled or rejected. If fulfilled, its value will be the value it resolves with, and if it encounters any error, its value will be the value it rejects with (the error object).

For example, when we make API requests to the server, it immediately returns a promise with _pending_ state. If the API call is successful, the state of promise changes from **pending** to **fulfilled**, and if the API request fails, then its state changes from **pending** to **rejected**.

## Creating a Promise in Javascript

```javascript
const promiseExample = new Promise((resolve, reject) => {
  const condition = true;
  if (condition) {
    resolve("Resolve with Any type of data (objects, arrays, strings, etc...");
  } else {
    reject("Error description.");
  }
});
```

So, we can create a promise by using the `new Promise()` constructor. It takes a function as an argument. This function takes two callback functions, `resolve` and `reject`. Whenever you want to fulfill the promise, you can call the `resolve` callback function and pass the value to it. To reject a promise, call the `reject` callback, providing some error message.

## Using the Promise

We can use the above promise creation example.

#### .then()

```javascript
const promiseExample = new Promise((resolve, reject) => {
  const condition = true;
  if (condition) {
    resolve("Promise Fulfilled.");
  } else {
    reject("Promise Rejected.");
  }
});

promiseExample.then((result) => {
  console.log(result); // Promise Fulfilled.
});
```

So, the `.then()` method takes a callback function that executes whenever the promise resolves (or is fulfilled). The callback itself takes a parameter to store the actual result returned from the promise.

**Note:** The `.then` also takes a second parameter, a callback function, to handle errors, but there's a better way.

#### .catch()

```javascript
promiseExample.catch((err) => {
  console.log(err); // Promise Rejected.
});
```

The `.catch()` method also takes a callback that executes whenever the promise rejects (or fails). This callback takes an error parameter to catch the error information.

## Chaining of Promises

Suppose we have to perform multiple asynchronous tasks. In that case, we use promise chaining.

```javascript
// Resolve promise after 1 sec
const promiseExample = new Promise((resolve, reject) => {
  setTimeout(() => { 
    resolve("data of 1st Promise");
  }, 1000);
});

promiseExample
  // 1st .then()
  .then((dataOfFirstPromise) => { 
    console.log(dataOfFirstPromise); // data of 1st Promise

    // simulating API call which resolves after 1 sec.
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("data of 2nd Promise");
      }, 1000);
    });

  })
  // 2nd .then()
  .then((dataOfSecondPromise) => { 
    console.log(dataOfSecondPromise); // data of 2nd Promise
  })

  .catch((err) => console.log(err));

```

Few things to note here - 

1. The `.then()` and `.catch()` methods always returns a promise so that we can again use `.then()` and `.catch()` on them and chain the promises.

2. In the above example, we use two `.then()` methods. So, to consume the result of the first `.then()` method, we always need to return that value from it. In this case, we `return` a promise from the first `.then()` method.

3. We use `.catch()` to catch the error if it occurs in any of the promises. This is the main reason we use `.catch()` instead of the second parameter of `.then()`. The `.catch()` method always catches the error either if it occurs in promise or the `.then()` method.

In the above example, we first create a promise which resolves after 1 second. After that, we call `.then` on the promise and get the result of the first promise in parameter `dataOfFirstPromise`. Now, if we want to fire another API request only after the 1st promise resolves, we can do that here. So we simulate API request with 2nd promise that resolves after 1 second, and we can get the result of 2nd promise in the 2nd `.then()` method. You can chain as many `.then() 's and `.catch() 's as you want.

That is all about Promise chaining.

Well, this was a brief introduction to promises. Thanks for reading.

![](https://media.giphy.com/media/13HgwGsXF0aiGY/source.gif)