Consuming Promises in Javascript

Consuming Promises in Javascript

Introduction

Promises are one of the most important things that modern Javascript has to offer and there's no way a web developer can avoid using them. It will definitely be your interviewer's favorite topic if you're applying for a full-stack or a front-end role. Therefore in this blog, we are going to understand promises, their life cycle, and how to consume them in your web application to perform Asynchronous tasks in an efficient way. So Let's start by understanding what promises is.

What are Promises?

A Promise is an object that is used as a placeholder for the future result of an asynchronous operation or in simpler terms Promise is a container for an Asynchronously delivered value. One of the most widespread uses of Promise is to handle AJAX calls (response from the AJAX calls).

By using Promises we no longer require an event and a callback function to handle the Asynchronous results. We can also chain Promises for a sequence of Asynchronous operations instead of nesting them and hence escaping the callback hell. Promises were introduced in ECMAScript 2015, also known as ES6 and are compatible with almost all modern-day browsers.

Life Cycle of a Promise

A Promise for instance can be :

  • Pending: Before the future value is available

  • Settled: Asynchronous task has been completed

  • Fulfilled: The Asynchronous task has been completed successfully and the return value is now available

  • Rejected: Some error occurred while completing the asynchronous task and which leads to Promise getting rejected.

For example, if I try to call an API using fetch and try to console the output we can see that it returns a Promise which was in the pending state at the time of executing that console statement because there will be a delay in getting the response from the server the promise won't contain the final value immediately.

Now let's see how we can actually consume Promises in the next section.

Consuming Promises

Let's take an example of a fetch API call which as we saw returns a promise and consume it.

As we can see the fetch returns a promise which is in the pending state but surely after some time it will be either by either getting into Fulfilled state or by going into Rejected state.

For now, let's assume that the API call will always be a success and promise will be fulfilled. For that, we can use then() method which is available for all the promises. Inside the then() method we need to provide a callback function that we want to execute as soon as the Promise is fulfilled.

Now in order to get the actual data returned from the API we need to use json() method which is also an Asynchronous task and hence can be handled by another then() method. The two then() method calls in sequence is basically a small chaining.

Until now we always assumed that our AJAX calls were fulfilled but however, an important part of Web Development is to handle errors and in a Promise, if an error occurs then it goes to the rejected state. To handle the rejection state we can pass another callback function that will have an error as a parameter and is executed whenever an error occurs while executing the promise. Let me demonstrate this by giving the wrong URL to fetch.

Now instead of having a callback function in every then() method for a chain of promises we can have a common catch() method which will catch the error throughout the chain of promises.

Notice in above example, for the first fetch call I have provided the wrong URL while in the second fetch call I have done syntax error in the second then() method and catch() method was able to catch both the errors in the chain of two then() method.

We also have finally() method which is executed no matter what state a promise goes to it will always get executed. The most common use case of using finally() is to stop loader once the promise is settled.

Conclusion

In conclusion, Promises are an essential feature of modern JavaScript that simplifies asynchronous programming. They provide a clean and organized way to handle asynchronous operations, making code more readable and maintainable. When working with Promises, it is important to remember to handle both resolved and rejected states, and to use methods like .then() and .catch() to chain and handle Promises. By mastering Promises, you can create more efficient and robust JavaScript applications that are better equipped to handle complex, asynchronous tasks.

Did you find this article valuable?

Support Mehul Gupta by becoming a sponsor. Any amount is appreciated!