Promises in JavaScript

Promises in JavaScript

In this article, you will learn about JavaScript promises, what they are, and how to use them effectively.

prom1.png

What is Promise in JavaScript?

A promise is an object that may produce a single value in the future after some time. Either it will be a resolved value or a rejected value.

As you might know, JavaScript is a single-threaded language. That means it has one call stack and is synchronous.

Promises are the ideal choice for handling asynchronous operations most simply and provide better error handling than callbacks. In other words, Promise makes JavaScript behave asynchronously, which makes this language versatile.

WORKING OF PROMISE:

Let's understand this with an example:

Suppose that you promise to lose 5kgs weight by next month.

You don’t know if you will spend your time and effort to lose weight until next month. You can either be losing weight or not.

Promise has three possible states:

  • Pending: You don’t know if you will lose 5kg by the next month.

  • Resolved/Fulfilled: You lost 5kgs by the next month.

  • Rejected: You don't loose weight at all.

A promise starts in the pending state, which indicates that the Promise hasn’t been completed yet. It ends with either resolved/fulfilled (successful) or rejected (failed) state.

LET'S WRITE A SIMPLE CODE TO UNDERSTAND THE PROMISE:

To create a promise in JavaScript, you use the Promise constructor as shown below:

let prom = new Promise((resolve, reject) => {
  let a = 5 + 5;
  if (a === 10) {
    resolve("This resolve should come in the then block");
  } else {
    reject("This reject should come in the catch block");
  }
});

prom
  .then((msg) => console.log("then block -->", msg))
  .catch((msg) => console.log("catch block -->", msg));

when we run above code we get following output:

'''then block --> This resolve should come in the then block'''

As, 5 + 5 = 10 the a = 10 so it will execute if(){} block and it will resolve the promise. If we change a = 5 + 5 to a = 5 + 1 and keep rest of the code same we will get following output as it will execute the else{} block and it will reject the promise.

'''catch block --> This reject should come in the catch block'''

LET'S SEE THE USE CASE OF PROMISES BY SIMPLE REAL WORLD EXAMPLE:

// Let's assume that this products variable is a data that is
// already present in our database
const products = [
  {
    title: "Mobile",
    price: "13999",
  },
  {
    title: "Laptop",
    price: "40999",
  },
  {
    title: "Headphones",
    price: "3999",
  },
];

let createProduct = (product) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // let's define an error variable
      let error;

      if (product) {
        // if we receive a product_details that means there is no error
        error = false;
        // so we will push the received product in our existing products' array in our database 
        products.push(product);
      } else {
        // if we don't receive a product that means there is some error
        error = true;
      }

      if (!error) {
        resolve();
      } else {
        reject("Some error occurred");
      }
    }, 3000);
  });
};

let fetchProducts = () => {
  // here setTimeout is imitating time require to fetch data/api from server
  setTimeout(() => {
    products.forEach((prod) => {
      console.log(prod.title);
    });
  }, 1000);
};

createProduct({ title: "iPhone", price: "100,000" })
  .then(fetchProducts) // if product created successfully we will fetch all the products
  .catch((error) => console.log(error)); // if any error occurs we will console log the error which we have passed in reject()

console.log("These are further lines of code.\n");
  • Here, we are creating a product and as soon as we create a product we want to fetch all the products that are stored in the database, including newly created product.

  • In case any error occurs we want to reject the promise, catch that rejection and instead of crashing our app, we want to simply console log the error.

Take a look at the following code:

createProduct({ title: "iPhone", price: "100,000" })
  .then(fetchProducts) // if product created successfully we will fetch all the products
  .catch((error) => console.log(error)); // if any error occurs we will console log the error which we have passed in reject()

Now, when we pass { title: "iPhone", price: "100,000" } in the createProduct() that means we are receiving a product (details of the product that has to be created) and there is no error. That means our Promise got resolved. So, it will run fetchProducts() by executing .then() block.

Output of the above code:

nres.PNG Now, take a look at the following code:

createProduct()
  .then(fetchProducts) // if product created successfully we will fetch all the products
  .catch((error) => console.log(error)); // if any error occurs we will console log the error which we have passed in reject()

Now, If we don't pass { title: "iPhone", price: "100,000" } in the createProduct(), that means we are not receiving a product and there is an error. That means our Promise got rejected. So, it will show an error message by executing .catch() block.

Output of the above code:

nres1.PNG

CLOSING THOUGHTS:

In short, a Promise is an object that once called upon, will eventually resolve or reject and return a response based on some criteria that is specified within the Promise object.

Chances are that, if you have ever used fetch() or axios() to get some sort of a JSON response back from an external API, such as fetching weather information from openweathermap (see following image) you have been interacting with a Promise object this whole time.

# Axios is promise-based
Axios({
        url: 'https://api.openweathermap.org/data/2.5/weather',
        method: "GET",
        headers: {
          Accept: "application/json",
        },
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

If you are reading this, you are quite familiar with using axios() or fetch() in real-world applications. Hopefully, by reading this post, you realized that you were almost already a Promise guru, and I hope you found out some interesting behind-the-scenes picture of how Promises work on the other side of the axios() or fetch().

Thank you for reading!

Make sure to subscribe our newsletter on blog.learncodeonline.in and never miss any upcoming articles related to programming just like this one.

I hope this post will help you in your journey. Keep learning!

My LinkedIn and GitHub .

Did you find this article valuable?

Support Learn Code Online by becoming a sponsor. Any amount is appreciated!