DEV Community

Akanksha
Akanksha

Posted on

Promises in JavaScript

Hello, everyone!!!
This is my first blog and this blog will give you basic understanding of how promises work in JavaScript.

What is JavaScript?
JavaScript often abbreviated as JS, is the Programming Language for Web. It is a single-threaded language, meaning it can do only one task at a time. It cannot run two pieces of code simultaneously. When one piece of code gets complete, the piece can start executing/running.

Previously, before promises were introduced, callbacks were used to handle asynchronous operations. But for multiple asynchronous operations, callbacks can create callback hell leading to unmanageable code.

What is a Promise?
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. - MDN Web Docs

A Promise in JavaScript is just like a promise in real-world. Lets take an example:- Your friend promised to get you a chocolate, when he/she meets you. Now, your friend has just made a promise, you don't know whether he/she will really get you a chocolate or not. So, we can say that the promise is pending. If he/she gets you a chocolate, then promise is completed. If he/she doesn't get you a chocolate, it means that promise is rejected.

Similarly, in JavaScript, a Promise is an object that holds the future value of an asynchronous operation.

A Promise has 4 States:

  1. Fulfilled or Resolved - Action related to Promise succeeded. It
    means that the promise is completed.

  2. Rejected or Unresolved - Action related to Promise failed. It
    means that the Promise is not completed due to some error.

  3. Pending - It means that the Promise is neither fulfilled nor
    rejected.

  4. Settled - It means that Promise has been fulfilled or rejected.

JS Promises

Creating a Promise
A Promise object can be created using its constructor and new keyword.

var myPromise = new Promise(function(resolve, reject) => {
        const x = 2;
        const y = 2;

     if(x == y){
        resolve();
     }else{
        reject();
     }
});

myPromise
  .then(function(){
      console.log("Success");
   })
   .catch(function(){
       console.log("Error");
   });
Enter fullscreen mode Exit fullscreen mode
Output:
Success
Enter fullscreen mode Exit fullscreen mode

A Promise constructor takes only one argument, a callback function which is also known as executor function. The callback function takes 2 arguments: resolve and reject.
In the above example, if the value of x is equal to the value of y, then promise is resolved. If value of x is not equal to y, then promise is rejected.

Consuming a Promise
Now that we know how to create a promise, lets understand how to consume a promise. We consume a promise by calling then() and catch() methods on the promise.

.then() - This method is invoked when a promise is resolved or rejected. It takes two parameters.

.then() Syntax : promise.then(successCallback, failureCallback)

The first function that is successCallback is executed if promise is resolved and result is received.
The second function that is failureCallback is executed if promise is rejected and error is received. This is optional. It is always better to use .catch() method.

.catch() - This method is invoked when promise is rejected or some error has occurred in execution. This method is used for handling errors.

.finally() - When is promise is settled(i.e. either resolved or rejected), the callback function in finally() method is invoked. This method is called regardless of whether our promise was rejected or resolved.

var promise = new Promise((resolve, reject) => {
          resolve("Promise resolved");
});

promise 
   .then((data) => {
      console.log(data);
})
.catch((error) => {
   console.log("error");
})
.finally(() => {
   console.log("Finally block is executed");
});
Enter fullscreen mode Exit fullscreen mode
Output:
Promise Resolved
Finally block is executed
Enter fullscreen mode Exit fullscreen mode

Conclusion
We learnt what are promises and how to use them. We also saw how to create promises and consume them.

I hope you found this blog helpful!!!

Top comments (0)