JavaScript Promise

JavaScript Promise is one of the great ways to handle asynchronous operations. Promise in JS is similar to real-life promises. When we make a promise, it is a guarantee that it is for the future, and it has two outcomes, it will either be kept or won’t. For instance, your father promises you that he will get you a laptop next week. So you don’t know whether you will get a laptop next week or not.

So in this blog, you will learn about JavaScript Promise with the help of coding examples. However, to understand promises better, first, check out this blog Callback functions in JavaScript.

1. What is JavaScript Promise?

Promise in JS is an object that may give single output in the future; that output is either a resolved value or a rejected one with reason. It is used to find if asynchronous operations are resolved or not.

A promise may have one of three states:

1. Pending: When you fetch some API data using Promise, it will start from a pending state, meaning it is not fulfilled yet.

2. Fulfilled: If your data fetched successfully, the Promise will be in the fulfilled state. onFulfillment() function will be called (eg. resolve() ).

3. Rejected: If an error while fetching the data, the Promise will move to the rejected state. onRejection() function will be called (eg. reject() ).

JavaScript Promise
3 States of Promise

2. How to create Promise

To create the promise object, we use the Promise () constructor.

A promise() constructor takes 2 functions as an argument i.e. resolve() and reject(). If the promise resolve successfully resolve() function is called and if an error occurs, reject() function is called.

Let’s have one example to understand Promise in detail:

let promise = new Promise((resolve, reject) => {
  let promiseCount = true;
  if (promiseCount) {
    resolve("The promise resolve successfully.");
  } else {
    reject("A error occur while resolving the error.");
  }
});

promise.then((message) => {
  console.log(message)
}).catch((message) => {
  console.log(message)
})

In the above example, the Promise is resolved as promiseCount is true.

3. Then() Method

After the Promise gets resolved, we have to decide what to do next. The then() method is called after the Promise gets resolved, and inside this method, we can define what we can do next.

For instance, let’s have one example:

promise.then((message) => {
  console.log(message)

4. Catch() Method

Now we know that then() method is called after the Promise gets resolves. But what if the Promise fails?

The catch() method is called after the Promise gets rejected. We can attach the catch() method right after the then() method.

For instance, let’s have one example:

promise.then((message) => {
  console.log(message)
}).catch((message) => {
  console.log(message)
})

If the Promise gets rejected in the above example, it will directly jump to the catch() method.

5. Finally() Method

Finally() method is also used with Promise. The finally() method execute the statement in both cases. That means finally() method will get executed either if the Promise gets resolve or gets rejected.

For instance, let’s have one example:

let promise = new Promise((resolve, reject) => {
  //could be resolved or rejected
    resolve("The promise resolve successfully.");
});
promise.finally((message) =>{
  console.log("Hello I am finally block example.")
});

Output

"Hello I am finally block example."

6. Promise Chaining

If there is a single request, then we can handle it with Promise. But what if we have multiple requests? Then we can start another Promise right after the first one gets resolved by the Promise chaining method.

let promise = new Promise((resolve, reject) => {
  let promiseCount = true;
  if (promiseCount) {
    resolve("The promise resolve successfully.");
  } else {
    reject("A error occur while resolving the error.");
  }
});

promise.then((message) => {
  console.log(message)
}).then((message) =>{
  console.log("Hello I am an example of Promise chaining.")
}).catch((message) => {
  console.log(message)
})

Output

"The promise resolve successfully."
"Hello I am an example of Promise chaining."

Hopefully, now you have an overview of what JavaScript Promise is and how we can use them, and may you have already studied the Callback functions from my previous blog. After learning both of them, you may wonder that both Promises and Callback functions handle asynchronous operations. So what is the use of Promise when we have a Callback function?

Let’s discuss

7. Promise Versus Callback Function

For many years the callback functions have been used alone to handle asynchronous operations but using promises in many cases is a great option.

You can easily handle single asynchronous operations using a Callback function, but what if there are multiple async operations? Using a Callback for multiple async operations can land you in a problem called Callback hell or pyramid of doom.

firstCallback(function(response) {  
    secondCallback(response, function(nextResponse) {    
        thirdCallback(nextResponse, function(finalResponse) {     
            console.log('Final response: ' + finalResponse);    
        }, failureCallback);  
    }, failureCallback);
}, failureCallback);

In the above code, you can see how difficult it is to understand this code.

However, if we do this code using promises, it will be much easier and cleaner as we can attach callbacks rather than passing them.

firstCallback()
  .then(function(response) {
    return secondCallback(response);
}).then(function(nextResponse) {  
    return thirdCallback(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);

8. Conclusion

Hopefully, now you have a complete overview of what Promises is and how they differ from Callback functions. In our next blog, we will discuss JavaScript async/await.

Some links on this page are affiliate links. This means that if you choose to make a purchase, we may earn a small commission at no extra cost to you. For more information, Go here

Leave a Reply

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