Promise in Javascript

Promise in Javascript

What is Promise in Javascript?

In terms of javascript promise is nothing but an Object. In general terms promise is similar to real life promise.

For example

Suppose A and B are very good  friends. And A is going out for some work. On the same time if B will ask him that when you will be back please bring some items to eat. If you will not find any thing there, then do let me know via call. So here may be possibility that A can bring the items or might not. So either he can full-fill the  promise or reject the promise.

So on the similar concept our javascript promises also working. It is one of the way to deal with asynchronous operations in javascript.

When promises created , it’s like a proxy for a value which is not necessarily known. It allows to associate handlers with an asynchronous action’s eventual success value or failure reason.

A Promise can be in one of the three state :

  • pending: It’s an initial state where promise is neither fulfilled nor rejected.
  • fulfilled: It means task or operation is completed or fulfilled.
  • rejected: It means task or operation is failed or rejected.

How to create the Promise?

let promise = new Promise((resolve, reject) => {
     // Some Action
});

In the above syntax you can see that we have created the promise object by using new keyword. It means we have used the Promise Constructor to create the promise object.  And this Promise constructor takes function as an argument which is called as executor function.  And this executor function also takes two arguments which is resolve and reject functions.

When promise is full-filled or completed the resolve() function is called and if promise is not full-filled then reject() function is called.

Promise

Lets understand it by example:

// Produce Promise
let flag = true; 
let promise = new Promise((resolve, reject) => {
     setTimeout(() => {
         if(flag) {
            resolve("Promise is resolved");
         } else {
            reject("Something went wrong hence Promise is rejected");
         }
     }, 2000);
});



// Consume Promise
promise.then((response) => {
       console.log(response);
}).catch((error) => {
       console.log(error);
})

Output: Promise is resolved

Lets understand the code step by step –

  • In this example we are not using actual API hence we are handling it through one flag. Thats why taken flag = true. In real time with API we can test this promise.
  • Then we have created promise object by using new keyword and passed one executor function on it. And inside executor function two arguments are passed which is resolve and reject.
  • Now we have used setTimeout function to get the asynchronous action. And which is having 2 second of delay time.
  • Inside setTimeout we have checked that if flag is true then we have called the resolve() function. Which means our promise is  full-filling or completing. And inside resolve we have passed one message that "Promise is resolved".
  • Similarly we have handled the else block where we have called reject() function. Which means promise is not resolved. And passed one message that "Something went wrong hence Promise is rejected".
  • By above steps we can produce the promise. Now will see how to consume it.
  • Now whatever promise we have created , we need to call them, So that we can get the response that promise is fulfilled or not.
  • We have used then() method  if promise is resolved. So inside then() method we simply display the response coming from the resolve() method.
  • If promise is rejected then it can be handled inside catch() method. So inside catch() method we have display error coming from the reject() method.
  • So if flag is true then output will be "Promise is resolved" and if flag is false output will be "Something went wrong hence Promise is rejected".

Why Promise?

  • Main advantages of using promise is to deal with the asynchronous code in a better way.
  • To avoid the callback hells.
  • Improves code readability.

Below are the list of methods which is used in promise in this article.

Method Description
resolve(value) Return a new promise object which is resolved with the value.
reject(reason) Return a new promise object which is rejected due to some reason
then() Handle the callback when promise is resolved.
catch() Handle the callback when promise if rejected.

Conclusion:  Promises are similar to callback function. Both are used to handle the asynchronous operations. There may be the case where we need to execute two or more than two asynchronous operations back to back. And next operation is depends on the previous operations response. So it can be handle by Promise Chain. So in upcoming article we will discuss about the promise chain.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *