Javascript Promise

Javascript Promise: Making asynchronous operations friction-less

It is common knowledge among technology enthusiasts that Javascript is a synchronous programming language which can be turned into an asynchronous one with the help of the callback function. This was the route followed up until now. But now the tables have changed with the rapid adoption and use of Javascript Promise.

Promises: A comparison- In Javascript and real life

Before we get into the technicalities of understanding the reasons for the shift to promises from callback or its use cases, let’s delve a little into relating Javascript promise to the ones we make in real life. The analogy is quite simple and will give you a better understanding of what promises is all about.

For starters, a promise is a sort of a commitment that may or may not be fulfilled in the future. This is true for both real life and Javascript. This means that a promise may result in one of three states i.e. Pending, Fulfilled or Rejected.

To take a real-world example, consider a promise you make to your friend to help him/ her out with their work. While your friend has an assurance that you might help them out in the future, there are 3 possibilities of action-

  1. Pending- Your friend is unsure if you will help out or not
  2. Fulfilled- You kept your promise and helped out your friend
  3. Rejected- You don’t help out your friend

Javascript promise can also be seen as such an assurance representing an eventual value that may result from an asynchronous operation. The actual result will only be known once the asynchronous operation is complete. These leaves behind 3 possibilities-

  1. Pending- When the asynchronous operation is underway and the outcome of the promise is uncertain
  2. Fulfilled- When the asynchronous operation is complete and the promise receives a value
  3. Rejected- When the asynchronous operation has failed and the promise will never receive a value.

Like real life, when the promise in javascript is pending, it can transition to either of the other two categories (fulfilled or rejected). However, once it enters the other two, there is no going back.

Why Promise in Javascript?

A lot of developers wonder why the switch to promise has been so hyped and rapidly adopted. Well, the reason is the same as for any other switch, promises make life simpler. As mentioned earlier, Javascript by its nature is synchronous and callbacks were used to conduct asynchronous operations. Javascript promise makes the managing, composing and execution of asynchronous operations easier and frictionless. As a step up to the traditional method of using callbacks, a promise is a technological advancement that allows coders to even deal with asynchronous errors.

For all developers out there, the promise seems to be a way out of the ‘callback hell’ most experience at some point or the other. In a nutshell, the switch to promise is a result of its ability to deliver a cleaner, neater syntax with an effective methodology to handle asynchronous operations and make them look synchronous.

Understanding how Promises work

To understand how promises work, it is important to understand that a promise consists of 2 parts- One which creates the promise and defines the conditions of success or failure. The other describes the next steps when the condition succeeds or fails.

Creating a Promise

A promise object is generally created a new keyword using what is known as an ‘executor function’ based on 2 parameters.  Resolve or the first function results when the asynchronous operation is successful and returns the result as a value. The second function or reject results when the operation has failed along with a reason for the failure, generally displaying the error.

Chaining Promises

It is quite normal to need multiple promises in a single asynchronous operation. This can be achieved by using what developers are referring to as chaining of js promise. The process is relatively simple to understand. You can just chain the .then () function of the first promise returning the next promise and so forth.

Chaining of promises raises the question of sequential vs simultaneous execution. Promise.all() and Promise.race() can be adopted respectively. The former command evaluates all promises and only executes the .then() method when all promises have finished. The latter, on the other hand, starts executing the .then() method as soon as one promise has completed execution.

Handling Errors

As mentioned, the execution function then() is based on two callbacks- resolve and return. Using another function catch() can make your life easier. In case the promise is rejected, the catch() function can be used to handle the promise rejection and resolve the error. This function not only makes asynchronous callback frictionless but also makes handling errors a piece of cake.

Javascript Promise: Advantages

To understand what makes JS promise an appealing object to adopt, let’s look at a list of advantages it offers-

  1. A clean code

Promise requires a significantly less amount of code for the effective asynchronous operation. As opposed to the traditional callback function, the coding for promises is far more clean and concise. The benefits are two-pronged. Firstly, the developers have to write much less code, saving them a lot of time. Secondly, the developers can easily avoid nesting of the code. Additionally, the composition becomes easier. Promise allows developers to reuse many synchronous tools. Thus, using promise allows users to save time and a decent amount of code.

  1. Better readability and visualization

Resulting from its ability to create clean and concise codes, js promise also ensures the creation of a legible code. Since the code is shorter, it is easily readable. Additionally, it caters to better visualization of the execution flow. This allows developers to move from callback hell to a happy chaining land.

  1. Error handling

Finally, promise makes the handling of rejection of an asynchronous operation a lot easier. Firstly, it provides a unified platform to deal with problems of both asynchronous errors and normal exceptions. This prevents time and energy wastage in dealing with multiple platforms. Secondly, promise allows developers to chain then() and catch() function to not only get notified about rejection but to also understand the underlying error.

The Final Word

To cut a long story short, it goes without saying that Javascript promise is definitely an assurance that is making asynchronous operations frictionless. By taking care of all the core needs of the developer, right from chaining to error handling, the promise has become a one-stop solution to facilitate asynchronous tasks. What is praiseworthy is the fact that it has not only overturned the problems of callback hell but also augmented the whole experience by adding some major forward-looking functionalities. Thus, js promise is definitely a promise into redefining Javascript’s asynchronous journey.

Recro’s Blog

We share the latest trends, tutorials, resources around software development to help developers grow personally and professionally.


Recro Awaits You

recro awaits you