DEV Community

Cover image for Introduction to Promises in JavaScript.
Abhishek Jain
Abhishek Jain

Posted on • Updated on

Introduction to Promises in JavaScript.

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

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

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.");
  }
});
Enter fullscreen mode Exit fullscreen mode

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()

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.
});
Enter fullscreen mode Exit fullscreen mode

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()

promiseExample.catch((err) => {
  console.log(err); // Promise Rejected.
});
Enter fullscreen mode Exit fullscreen mode

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.

// 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));

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (10)

Collapse
 
flashamarillo profile image
Diomar Villarroel

was awesome :D

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Thank you 🙂🙂

Collapse
 
flashamarillo profile image
Diomar Villarroel

please make a new post about Fetch API and try-catch

Thread Thread
 
abhishekjain35 profile image
Abhishek Jain

Sure, maybe next time :)

Collapse
 
dario_wd_coding profile image
Dario Presutti

Thanks to sharing! In this moment of my live i switch completely to observable and reactive programming. I'm using them in a very big project at work and a fallen completely in love with them.

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Yeah, both are good in their own ways. 😁😁

Collapse
 
anantt08 profile image
anantt-08

Great Buddy Keep Posting Stuffs !

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Thank you. 😄

Collapse
 
uddeshjain profile image
Uddesh

Well explained. 👏👏

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Thank you. 😁😁