Promises in jQuery

In the recent lesson about AJAX we saw how to make a server request in the background (asynchronous), and then handling the server response in a function. If a second asynchronous server request depends on the first one, it becomes messy to manage the dependencies. For example, the second asynchronous server request can be initiated in the response handler function of the first server request. This leads to long chains of calls that can be hard to read and make sense of.

To make composition of multiple asynchronous requests more manageable, the concept of a Promise was introduced. A Promise basically represents an action with an eventual outcome. By representing this eventual outcome as a promise object, the interaction between multiple promise objects can easily be expressed even when their results are not yet available. The Promises/A+ specification details the behavior and interface of promise objects. This way there is a standard interface for interacting with promises, independent of the actual promise-implementing library.

jQuery provides the Deferred Object which is a promise object. When making an AJAX call with jQuery’s $.ajax method (or with one of the convenience methods like $.get), the returned object implements the promise interface, just like the Deferred object. This way, multiple jQuery AJAX call objects can be coordinated using the mechanisms provided by promises.

First, let’s look at some other means of making asynchronous calls. The built-in JavaScript functions setTimeout and setInterval can be used to make delayed function calls.

Delayed function execution

The JavaScript setTimeout function can be used to call a function in the future, by specifying the function to be called and the time (in milliseconds) to wait until the function gets called. Here’s an example:

1    function sayHello() {
2        alert('hello');
3    }
5    setTimeout(sayHello, 5000);

Here, the sayHello function will show an alert popup box with the text “hello”, but only after 5 seconds.

The function setInterval will also call the function after the specified delay, but it will repeatedly call the function:

1    function sayHello() {
2        alert('hello');
3    }
5    setInterval(sayHello, 5000);

Here, the sayHello function will be called every 5 seconds. Note: when using setTimeout or setInterval, the queued function call can be canceled. To cancel the call, use the JavaScript built-in function clearTimeout which takes the timer ID returned by a previous call to setTimeout or setInterval.

For example, the following will start a recurring call to function logGreeting every second. After 8 seconds, it will stop and cancel the recurring function calls:

1    function logGreeting() {
2        console.log('hello at ' + new Date());
3    }
5    var timerId = setInterval(logGreeting, 1000);
7    setTimeout(function() {
8        clearTimeout(timerId);
9    }, 8000);

jQuery done method

When making a jQuery AJAX call, the done method can be used to attach a response handling function, to be called when the AJAX call finishes successfully. The jQuery AJAX call (e.g. methods $.ajax or $.get) returns an object that is referred to as “jqXHR”. The done method can be called on the jqXHR object to attach a function that will handle the eventual server response, if the server request was successful. Similar to done, there’s also a fail method to attach a failure handling function and an always method that will be executed regardless of whether the call was successful or unsuccessful.

Consider the following function that makes a call to the Open Weather API server:

 1    var API_KEY = '05e394dfc3d1b822698f06d759bc4c95';
 2    var WEATHER_SERVICE_URL = '';
 4    function fetchWeather(city, country) {
 5        var li = $('<li>Weather in ' + city.toUpperCase() + ': </li>');
 6        $('#weatherlist').append(li);
 7        var data = {
 8            q: city + ',' + country,
 9            APPID: API_KEY
10        };
11        return $.get(WEATHER_SERVICE_URL, data, function(result) {
12            if ( {
13                var weather =[0];
14                var kelvin = result.main.temp;
15                var fahrenheit = Math.round((kelvin - 273) * 1.8 + 32);
16                $('<span class="desc">' + weather.description + '</span>').appendTo(li);
17                $('<span class="temp">' + fahrenheit + ' F</span>').appendTo(li);
18            }
19        });
20    }

This function first adds a new <li> tag to the parent page’s <ul> list with the ID of “weatherlist”. It makes a call to for the specified city. When the request gets back the weather data, it adds the weather description and temperature. Note that this function returns the jqXHR object returned by the jQuery AJAX function. In this case it calls the $.get helper function.

Here’s a function that uses the jQuery done methods on the jqXHR object returned by the fetchWeather function:

1    fetchWeather('boston', 'usa')
2        .done( function() { fetchWeather('lima', 'peru'); })
3        .done( function() { fetchWeather('nashua', 'usa'); })
4        .done( function() { fetchWeather('hannover', 'germany'); });

When looking at the network requests in the Chrome Inspector’s Network tab, we see that the weather requests for lima, nashua and hannover happen after the first request for boston.

jQuery done

The last three requests basically start simultaneously. This is because the requests for lima, nashua and hannover are all attached as “done” handlers to the original boston request. The done method returns the original jqXHR object, allowing multiple method calls to be chained. That means the above is equivalent to doing the following:

1    var bostonRequest = fetchWeather('boston', 'usa');
2    bostonRequest.done( function() { fetchWeather('lima', 'peru'); });
3    bostonRequest.done( function() { fetchWeather('nashua', 'usa'); });
4    bostonRequest.done( function() { fetchWeather('hannover', 'germany'); });

jQuery Deferred object

In jQuery, the the Deferred Object can be used to represent a Promise.

Promises represent an eventual outcome. There is therefore some state attached to the promise object. The three states for promises are:

  • pending: This is the initial state. There is no outcome yet
  • fulfilled: The eventual value is available and the request is successful.
  • rejected; The eventual value is available and the request is unsuccessful.

jQuery’s $.ajax (and related) methods return a jqXHR function that implement the promise interface. In Many cases these “project objects” can be used as-is. If we need more control over a promise - like when the promise is fulfilled or rejected, and what the eventual value is - we can create a jQuery Deferred object to manage the promise.

Here’s one example of using a jQuery Deferred object to fetch the weather slowly:

 1    function fetchWeatherSlowly(city, country, prevCountry) {
 2        var promise = $.Deferred();
 3        var weatherRequest = fetchWeather(city, country, prevCountry);
 4        weatherRequest.done(function(apiJSON) {
 5            setTimeout(function() {
 6                if ( {
 7                    promise.resolve(apiJSON);
 8                }
 9                else {
10                    promise.reject("Error received from API: " + apiJSON.message);
11                }
12            }, 2000);
13        });
14        return promise;
15    }

The Deferred object (the promise) will resolve 2 seconds after the AJAX request from the fetchWeather call returns a response.

The Deferred/promise object gets resolved or rejected by calling the resolve or reject methods, respectively. Optionally, a value can be specified. In the above example, the fetchWeather AJAX call’s JSON response gets passed through to the Deferred/project object when it resolves.

Chaining promises together

There are cases when an AJAX call depends on a previous AJAX call’s response. If multiple AJAX requests need to be “chained” together, one way is to initiate the second AJAX call in the first AJAX call’s response handler function. When there are many calls in the chain, this quickly becomes hard to manage and reason about. Promise objects have a then method that can be used to chain together a sequence of promises. The then method takes two parameters. Both of these parameters are functions. The first function parameter is a success handler, which will be called if the promise resolved (completed successfully). The second function parameter is a failure handler, which will be called if the promise got rejected (completed unsuccessfully).

Here’s an example that fetches the whether of a few cities, but sequentially (not in parallel):

 1    fetchWeather('boston', 'usa')
 2        .then( function(bostonResponse) {
 3            console.log('got boston!', bostonResponse); 
 4            return fetchWeather('lynn', 'usa'); 
 5         })
 6        .then( function(lynnResponse) { 
 7            console.log('got lynn!', lynnResponse);
 8            // normally this function would fetch the weather for the city of Lima,
 9            // but we intentionally don't specify the city name to produce an error:
10            return fetchWeather('', '');
11         })
12        .then(
13            function(limaResponse) {
14                console.log('got lima!', limaResponse);
15                return fetchWeather('hannover', 'germany'); 
16            },
17            function(response) {
18                console.log('could not load lima!');
19                console.log('here is the response:', response);
20                return fetchWeather('hannover', 'germany'); 
21            }
22        )
23        .then( function(hannoverResponse) {
24            console.log('got hannover!', hannoverResponse);
25            return fetchWeather('canton', 'usa'); 
26        });

In Chrome Inspector’s network tab, we see that the requests run sequentially - one after the other:

jQuery then

Note: we intentially inserted a failed network request in the second then function call, where it makes a request with an empty city value. The following then function handles the error when the second function parameter gets called. Note: without the second function parameter, the then function would not contain a new promise object. The chain of then calls will continue as long as the previous then call returns a new promise for the next then call to act on.

Managing sets of promises

Sometimes we need to know when a set of promises have completed. jQuery’s Deferred object interface provides a when method that can be used to attach a function whenever the specified set of promises resolves.

Here’s an example that loads cities from three continents. As soon as all cities of a continent have loaded, a banner gets displayed on the page:

 1    var amsterdam        = fetchWeather('amsterdam', 'netherlands');
 2    var athens           = fetchWeather('athens', 'greece');
 3    var barcelona        = fetchWeather('barcelona', 'spain');
 4    var berlin           = fetchWeather('berlin', 'de');
 5    var cairo            = fetchWeather('Cairo', 'egypt');
 6    var capetown         = fetchWeather('Capetown', 'south africa');
 7    var chicago          = fetchWeather('Chicago', 'usa');
 8    var dallas           = fetchWeather('Dallas', 'usa');
 9    var dublin           = fetchWeather('dublin', 'ireland');
10    var edinburgh        = fetchWeather('edinburgh', 'scottland');
11    var houston          = fetchWeather('Houston', 'usa');
12    var johannesburg     = fetchWeather('johannesburg', 'za');
13    var la               = fetchWeather('Los Angeles', 'usa');
14    var london           = fetchWeather('london', 'gb');
15    var milan            = fetchWeather('milan', 'italy');
16    var montreal         = fetchWeather('Montreal', 'canada');
17    var nairobi          = fetchWeather('milan', 'kenya');
18    var nyc              = fetchWeather('New York', 'usa');
19    var paris            = fetchWeather('paris', 'france');
20    var philadelphia     = fetchWeather('Philadelphia', 'usa');
21    var phoenix          = fetchWeather('Phoenix', 'usa');
22    var rome             = fetchWeather('roma', 'italy');
23    var sanantonio       = fetchWeather('San Antonio', 'usa');
24    var sandiego         = fetchWeather('San Diego', 'usa');
25    var sanjose          = fetchWeather('San Jose', 'usa');
26    var toronto          = fetchWeather('Toronto', 'canada');
27    var vancouver        = fetchWeather('Vancouver', 'canada');
29    $.when(rome, paris, barcelona, london, amsterdam, dublin, athens, edinburgh, berlin, milan)
30        .then(function() {
31            $('#continents').append('<div>EUROPE loaded</div>');
32        });
34    $.when(nyc, la, chicago, houston, philadelphia, phoenix, sanantonio, sandiego, dallas, sanjose, toronto, montreal, vancouver)
35        .then(function() {
36            $('#continents').append('<div>NORTH AMERICA loaded</div>');
37        });
39    $.when(johannesburg, cairo, nairobi, capetown)
40        .then(function() {
41            $('#continents').append('<div>AFRICA loaded</div>');
42        });

Here is a screenshot, showing loading of the requests and the banners that appear when each continent’s group finished loading:

jQuery when docker build . -t docker push