Promises in Javascript

[Social9_Share type="horizontal"]

Promises in javascript

In this post, let us learn about promises in javascript

Let’s walk through

The Problem Statement

Let’s consider a scenario.
Here is a list of employees. On clicking on the View button on the Employee list, it has to show the respective user details and his income.


Solution – Using jQuery

First, let’s make a call to get the employeeId using employeeName which is being clicked now.

On its success call, let’s make two ajax calls. One for getting the employee details and the other for getting taxId.

Using the taxId available, we can get the incomeDetails of that taxId.

The complete code is given here.

This code works. But, this is not a good code. Why? A good code should be easily readable. I should be able to understand the flow in a quick glance. Think of a new person joining in the project and going through this code. He has to go through the full code several times to understand the full work flow.

Why Promises ?

The main challenge in the above code is we can make the next call only on the success of the first call and you have to write in the success property of the jQuery ajax call.

To improve the above code, comes the use of Promises. Instead of passing the success callback as an option in ajax call, the ajax call returns a promise so that it can be used elsewhere.

Solution – Using Promises

Let me first show you the change in code

You can see that the whole logic can be understood by the last three lines. This is possible because $.ajax method returns a promise.

When we make a asynchronous call, it returns a promise object immediately. This promise will be either resolved or rejected once the response is back. If it is resolved, success call back will be executed, if it is rejected, error call back will be executed.

Promise will have a then() method. In this method we pass the successCallback function and the errorCallback function

Advantages of Promise
  • It gives readability to the code
  • Maintenance of the code is easy
  • Since, we are getting the object outside of the asynchronous function, we can use it in different places.
  • All the then methods will be executed only, once the promise is resolved/rejected.

Different Implementations of Promise

There are different libraries for Promise implementation.
In jQuery$.ajax method returns a promise.
In Angular $http service call returns a promise.

You can also create custom promises. In the next post let’s discuss How to create custom promise using jQuery and AngularJS.

Till then,

Happy Coding

Post a comment