Promises in Javascript

Promises in Javascript

Asynchronous programming helps to execute multiple tasks at the same time without blocking the main thread of execution. Promises are a powerful abstraction for this that allows us to work with asynchronous operations in a more intuitive and manageable way. In this blog post, we'll take a closer look at Promises and learn how to use them in your JavaScript code.

What is a Promise?

A promise is an object representing the eventual completion of an async operation. Basically a container of future value. Promises are immutable. A Promise may have three states:

  • Pending: The initial state of Promise before it is resolved/rejected.

  • Fulfilled: Resolved state of promise

  • Rejected: Rejected state of promise due to an error or other exceptional condition.

Creating a Promise

Let's start by creating a simple Promise that resolves if the number of blogs is equal to 5, and rejects otherwise:

let numOfBlogs = 5;
let myPromise = new Promise((resolve, reject) => {
  if (numOfBlogs === 5) {
    resolve("Correct number");
  } else {
    reject(new Error("Failed Case!"));
  }
});

In our example, we check if the numOfBlogs variable is equal to 5. If it is, we call the resolve() function with a message that says "Correct number". If it's not, we call the reject() function with a new Error object that says "Failed Case!".

Handling a Promise

Here's an example of using then() to handle our Promise:

myPromise.then(
  function onFulfilledCallback(res) {
    console.log(res);
  },
  function onRejectedCallback(err) {
    console.log(err);
  }
);

In this example, we pass two callback functions to the then() method. The first function is called if the Promise is resolved successfully and receives the result of the operation as its argument. The second function is called if the Promise is rejected and receives the reason for the rejection as its argument.

Alternatively, we can use the catch() method to handle errors:

myPromise
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Chaining Promises

One of the most powerful features of Promises is their ability to be chained together. This allows us to perform a series of asynchronous operations in a specific order, passing the result of each operation to the next one.

Here's an example of chaining Promises:

fetch('https://api.example.com/data')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error(error);
  })
  .finally(() => {
    console.log("Finally called");
  });

Conclusion

Promises in JavaScript are a powerful tool for dealing with asynchronous code. By using Promises, we can avoid callback hell and create cleaner and more maintainable code.

In this blog post, we've covered the basics of Promises in JavaScript, including creating a Promise, using a Promise, and chaining Promises together. I hope this post has been helpful in getting you started with Promises in JavaScript!

Did you find this article valuable?

Support Vaibhav Garg by becoming a sponsor. Any amount is appreciated!