Promises in jQuery - Mastering JavaScript Promises (2015)

Mastering JavaScript Promises (2015)

Chapter 8. Promises in jQuery

In the last chapter, we learned how promises were implemented in Angular.js and how they provided benefit in the fast growing real-time web app industry. In this chapter, we will explore another very famous and useful JavaScript library for frontend web/mobile apps development.

jQuery is one the most used JavaScript libraries and it is recognized as one of the most maintainable, progressive, and easy to adopt libraries around. jQuery has also a credit to shrink the mile-long lines of code into plainer and simpler short code. This utility helped jQuery gain popularity beyond imagination. In this chapter, we will be looking at the history of jQuery, how it evolved, what is the basic way to use it, and how promises are playing a part in the maturity of jQuery. Let's start with the history of jQuery in brief.

From where it started?

The classical way of writing code in JavaScript was quite a tedious task. Since the language did not have many set rules, the code written in JavaScript was becoming unattainable and rewriteable. The way developers chose the names of their functions and variables was making simple functions nonreadable and thus not worthy to use in another project of a similar nature. Also, the fact was that JavaScript was considered as a second rated language in the computing world due to which not many people were using it seriously.

In August 2006 the birth of jQuery, enlightened the JavaScript world. John Resig, the brain behind jQuery, announced in his blog post that jQuery 1.0 was released. This was the first time when people really started taking JavaScript seriously and were convinced of its trustworthiness. Though JavaScript has been around since the early 90s (as described in the first chapter), it has seen many ups and downs. Finally, with the release of Firefox browser and jQuery, JavaScript managed to gain some credibility.

Behind the scenes – how does jQuery work?

jQuery is based on a simple line of write less, do more; within a few lines of jQuery code, you will be able to achieve more tasks than conventional ways of writing code. jQuery has made many tasks easy to conclude in a short time span. It also brings neatness and readability in code, which earlier, was rare in JavaScript.

After the arrival of jQuery, things started to change dramatically for JavaScript. Many new implementations started to come on the screen with much more mature approaches, but the place jQuery has gained was unmatched then and still is.

Having said this, let's come back to our topic: how does jQuery work behind the scenes?

It all rotates around the $ sign. The jQuery library provides the jQuery (); function, which allows you select elements just like CSS selectors. For example:

var itemsList = jQuery query("ul");

Or:

var itemsList = $("ul");

In the preceding line, the $ sign is the representation of jQuery. In JavaScript, the variable name can be anything, but must not start with a numeric value and must not include a hyphen. In this way, using $ is more convenient for the rules and easy to remember. You may also find functions like this:

window.jQuery = window.$ = jQuery;

Here the $ sign comes at the very end of the function, and this is the same sight you will notice in the jQuery source code.

The mechanism is when you call $() and supply a selector to it, you are actually creating a new jQuery object. In JavaScript, functions are objects too, which means $() has not only embedded a single object, but it may contain methods, variables, and multiple objects. So, you might use $.support for information on the current environment or you may also use $.ajax for an AJAX call to make an AJAX request.

Is your document ready to submit?

Sometimes, it can happen that you submit your document when its half finished without knowing that it still needs to be processed further. Such an event triggers a chain of events that will eventually make your page or app go into the service-fail mode.

Using jQuery, this is something that happens rarely as it provides the $(document).ready() method, which will help to complete of the processing the document. A simple example can be seen here:

$(document).ready(function() {

console.log('ready!');

});

The function will execute and will be passed to .ready() once the document is ready. We are using $(document) to create a jQuery object from the page's document. We will then call the .ready() function on that object, passing it the function we want to execute.

How to use jQuery

As we saw in Chapter 7, Promises in Angular.js, the documents related to Angular.js was the JavaScript file that was linked in HTML pages to call the functions; the same structure is used in jQuery.

jQuery is a JavaScript file that was linked in at the very beginning of our HTML file. This can be done in two ways: either call the file from its location on the Web or download the JavaScript file on your local hard drive and then embed the code. Either way it will work, but we prefer to use it from our hard drive.

The following lines of code show when we want to link a file from its remote location:

<head>

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.min.js"></script>

</head>

Or, we can download the file on our local hard drive and change the syntax like this:

<head>

<script src="js/jQuery/jquery-1.9.min.js"></script>

</head>

Here, src="js is indicating the local folder where JavaScript file exists.

In a nutshell, you can either use the already written jQuery by embedding it at the head of the HTML file using the URL or you can download it and make your own modifications. In both ways, your output will be generated on the screen of the browser.

The syntax

The real power of jQuery lies in its custom made syntax, which will help in selecting HTML elements and perform some action. Its syntax is quite straightforward and easy to remember, plus it's very neatly written. Here is a sample of jQuery syntax:

$(selector).action ()

The dollar sign ($) defines whether you will use jQuery, whereas the selector query is to find the HTML element and action defines what kind of action will be performed on selected elements.

Here are some examples that will explain how jQuery works using its syntax:

· $(this).hide(): This hides the current element

· $("p").hide(): The hides all <p> elements

· $(".test").hide(): This hides all elements with class="test"

· $("#test").hide(): This hides the element with id="test"

These are a few examples of hundreds of other methods provided by jQuery. For the complete reference on methods and APIs, here's the link for all your jQuery needs: https://api.jquery.com/.

Caching in jQuery

Let's discuss caching in brief specifically relating to jQuery and as a concept in general.

The concept of caching is as old as the Internet itself, at least with the modern day Internet. Developers are using it to store repetitive data and to reduce cost to server calls or to remember the connection between the user and server.

Caching helps in many ways to boost the performance of web apps by writing images and sending the session's information to the user's hard drive at a special location called the temporary storage. Mostly, this location is specifically created on the local hard drive and is there to deal with such type of data.

Say you are surfing an online shopping cart over your browser. At the very first instance, the site is being loaded to your temporary memory. This includes adding images of products and other meta information that marks the initial caching of that particular website. Now, say you have decided to purchase a product and signed in to the user's area of the shopping cart. This will cache your information in a little text file called a cookie, which holds the information about who you are and remembers the web server you are talking to. This is a flow of caching your information over the temporary location to reduce server calls, optimize navigation, and let the server remember your identity.

What does jQuery have to offer when it comes to caching and handing elements that need to cache? Let's take a look.

Caching in jQuery is offered by data function, and it's the same as any other function calls you make within jQuery. This function itself allows you to bind random data to random selectors. Most of the developers use it for manipulation with DOM elements, but this is not limited to it. You can add multiple selectors to bind to multiple references at a given time slot as the function takes care of it automatically; it's as simple and easy as this. However, how do the elements and their handlers stay in the memory?

jQuery follows the "name corresponds value" method to write and handle the elements in the memory. The unique part of it is the name of element can be same for many entries, but they must have to point to different DOM elements. In this way, reference by value comes into play and referring to a particular element will be faster and easy to traverse by the program using it.

Now, to add elements to the data function, we will follow a syntax similar to the one shown here:

$("#Textbox_").data("im_textbox1", value)

From here, you can see that we bind the selector with the data() function, and within the function, we supplied two parameters as the name and its corresponding value. In this way, we can bind as many selectors as we want to cache them up.

However, the story has a twist. You can write in cache using data(), but it won't remove data on its own. You have to remove it manually from the temporary memory. You can do it by calling out the removeData() method like this:

$("#Textbox_").removeData(value)

Of course, you can automate the function call of removeData() by writing some kind of cron/timer job function. However, this requires smart engineering and loads of dry run to that particular job as this can wipe out any important data from the temporary storage permanently, so it's advised to use such timer jobs in a very careful manner.

Overall, caching in jQuery is an essential component, and without this, you cannot optimize your application's flow and data traversing. Using jQuery cache will also optimize the number of server calls and will boost the performance of your piece of code.

A sample example

Before we start the prime topic of this chapter, we need to understand how we draft files that can use jQuery query. This will give us a better understanding of the code level working and will make us skilled to use promises in jQuery.

Let's start with selectors.

Selectors

Selectors enable us to select and manipulate HTML. We can use them to find HTML elements that are based on their IDs: classes, types, attributes, values, and much more stuff. These selectors are just like selectors in CSS, but with the jQuery touch. Here touch is all the selectors start with the dollar sign, $, followed by round brackets and dot, as shown in the following code:

<!DOCTYPE html>

<html>

<head>

<title> Selector in action </title>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("p").hide(); // this will able to select paragraph element from HTML

});

});

</script>

</head>

<body>

<h2>I am a heading </h2> <!-- this is the place from where the paragraph is selected -->

<p>I am a paragraph.</p>

<button>I am a button </button>

</body>

</html>

Have a look at the preceding code. The script tag right after the </script> tag is the place where the selector defines itself and then processes the requests. Once the page is loaded, it will say "I am a paragraph" with a button, and when you click on it, the name of the button will change to "I am a button" from "I am a paragraph." This all happened without any page change since jQuery was able to play with HTML elements on the go and display results on the same page. This is one helpful feature of jQuery out of the many that developers are using on a daily basis. Such binding, instantaneous computing is the reason why jQuery is the choice of many groups of developers.

Event methods

jQuery has many event-driven interfaces. These interfaces are invoked when you trigger some event. There are many events such as mouse click, double-click by mouse, keystroke, mouse hover, and touch. They are made simple by jQuery; all you need to do is write a few lines of code and the rest of the processing will be taken over by the jQuery library. Have a look at the following example:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

$(document).ready(function(){

$("h1").click(function(){

$(this).hide();

});

});

</script>

</head>

<body>

<h1> Click me to make me disappear </h1>

</body>

</html>

Okay, what will happen to the page when I click on the text that appears on the screen? Any guesses? Yes, it will disappear as I passed the value of the h1 tag into the jQuery function, which will then hide it when it senses the mouse has been clicked on it. This is how we normally used to play around with placeholders in the forms or text areas, but nowadays, forms have this ability built in.

Having said this, it's time to move on to the core of our chapter.

JavaScript before and after jQuery

There was a time when a simple mouse click can be caught by a simple function, element.onClick = functionName. This was good till the time another function came about that wanted to listen to the same click. This was solved by adding the addListenerEvent function from the DOM function. This had added as many possible listener functions, and we used to adopt this approach.

However, such happenings are meant to reoccur as we are now facing the same problem with AJAX calls. AJAX uses a single callback function and not only the jQuery $ajax(), but also the XMLHttpRequest object which has similar problems.

The solution – introducing promises in jQuery

The solution to the preceding problem was finally delivered in jQuery 1.5 as the deferred object. Before the deferred concept was introduced in jQuery, the typical AJAX call was something like this:

$.ajax({

url: "/testURL.com",

Success: TheSuccessFunction,

Error: TheErrorFunction

});

Can you guess what could be the output of this function? Yes, a single XMLHttpRequest object, which is quite expected for those who are still maintaining the apps built before jQuery 1.5.

Now, what dramatical change was introduced in jQuery 1.5. First of all, it's based on a specification of common JavaScript that defines common interfaces and can be extended as per the needs, and secondly, they are quite global and you can use these in similar services, such as Node.js.

After the addition of deferred objects in jQuery 1.5, the preceding code was rewritten like this:

var promise = $.ajax({

url: "/testURL.com"

});

promise.done(TheSuccessFunction);

promise.fail(TheErrorFunction);

If you want to write a more concise version of the preceding code, it can be achieved as follows:

var promise = $.ajax({

url: "/testURL.com"

});

promise.then(TheSuccessFunction,TheErrorFunction);

Likewise, there are a number of other advancements that were brought in by introducing promise in jQuery. In the following sections, we will take a closer look into how jQuery is getting its promises fulfilled.

Deferred in jQuery

Like in any other implementation of promises, Deferred also has its importance and value in jQuery. The power lies in the implementation of the concept, which is straightforward, yet very powerful. In jQuery, deferred has two important methods that are used to attach with three important events so that they can be linked to a callback. The methods are resolve and reject, and the events that can be attached with a callback are done(), fail(), and always(). Let's see it with an example:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

var deferred = $.Deferred();

deferred.done(function(value) {

alert(value);

});

deferred.resolve("hello $.deferred ");

</script>

</head>

<body>

<h1> $.deferred was just displayed </h1>

</body>

</html>

The thing to remember here is that callback will always be executed no matter whether deferred is resolved or not, but when you call the reject method, the failed callback will be executed. Having said that, our preceding example can look like this:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

var deferred = $.Deferred();

deferred.resolve("hello resolve");

deferred.done(function(value) {

alert(value);

});

</script>

</head>

<body>

<h1> sample example of Deferred object. </h1>

</body>

</html>

If we are to summarize what the $.Deferred object is; we can say it's just a promise that has methods, which will allow its owner to either resolve or reject it.

$.Deferred().promise() in jQuery

One of the shiny stars of Deferred is its promises. What this method can do? Well, it returns an object, and with nearly the same interface as Deferred. However, there is a catch. It's there just to attach the callbacks and not to resolve or reject.

This is quite useful in some other conditions, say you want to call out an API. This will not have the ability to resolve or reject the deferred. Such code will eventually fail as the promise here does not have a method.

Try executing this code, save it as test.html and run the file:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getPromise(){

return $.Deferred().promise();

}

try{

getPromise().resolve("a");

}

catch(err){

alert(err);

}

</script>

</head>

<body>

<h1> you have seen the error. </h1>

</body>

</html>

You will get an error like this:

$.Deferred().promise() in jQuery

So, as mentioned earlier, it returns an object and with nearly the same interface as that of Deferred. However, it's there just to attach the callbacks not to resolve or reject; this is the catch that we talked about earlier. Now, how can we resolve it? Simple. You can use promise as a return value for another function; let's try the following code:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

var post = $.ajax({

url: "/localhost/json/",

data: {json: JSON.stringify({firstMovieName: "Terminator", secondMovieName: "Terminator 2"})} ,

type: "POST"

});

post.done(function(p){

alert(p.firstMovieName + " saved.");

});

post.fail(function(){

alert("error! b/c this URL is not functioning");

});

</script>

</head>

<body>

<h1> you have seen the error. </h1>

</body>

</html>

When you run the preceding code, it will give you an error in the alert dialog box on the page, which it shouldn't when the URL passed in the URL variable is real. For the sake of understanding, let's assume the URL was proper and that it saved the value, the result will be like this:

$.Deferred().promise() in jQuery

The preceding code and the one before that has only one difference—you can add as many callbacks as you want, the grammar of the code is clean as it shows that we don't want an extra parameter in the method. Thus, you can ask promise in jQuery to perform some operations.

Projecting a promise in jQuery

In some cases, we have to just display the name of a promise. This will be much needed when you only want to see what the element can be or what operations you want to perform on an object. Using jQuery, we can easily achieve it by using the pipe() function.

Consider this code where we are projecting the result, which is an actor:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

var post = $.post("/echo/json/",

{

json: JSON.stringify({firstName: "Arnold", lastName: "Schwarzenegger"})

}

).pipe(function(p){

return "Name Saved >> " + p.firstName + " " + p.lastName;

});

post.done(function(r){ alert(r); });

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

The result of the code will be the full name, Arnold Schwarzenegger, displayed on an alert dialog box at the browser:

Projecting a promise in jQuery

As you can see, the projection of the result is an actor name used as an object. So, instead of deferred of a person, we have a deferred of Name Saved >> Arnold Schwarzenegger.

The pipe function can also be used to return the object from deep inside a method call. We can dig out an actor name and his IMDB rating, as explained in the following code:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getActorById(customerId){

return $.post("/echo/json/", {

json: JSON.stringify({firstName: "Arnold", lastName: "Schwarzenegger", rating: "8.0"})

}).pipe(function(p){

return p.rating;

});

}

function getRating(rating){

return $.post("/echo/json/", {

json: JSON.stringify({

rating: "8.0" })

}).pipe(function(p){

return p.rating;

});

}

function getActorRatingById(id){

return getActorById)

.pipe(getRating);

}

getActorRatingById(123)

.done(function(a){

alert("The rating of Actor is " + a);

});

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

When you run this code, it will give you an alert output on the browser, which will look like this:

Projecting a promise in jQuery

By the virtue of pipe(), we will dig into callback and on passing the correct parameters to the function getActorById(); we able to get our desired results displayed. In a similar manner, you can use pipe() to reject deferred inside the callback.

One more thing that you can do with pipe is recursive deferred. Say, you have an asynchronous operation at the backend of API calls, and you need to poll all the response sets before you can put them to use. You can ask pipe() to help you out.

Consider the following code that will help collect API responses and let you know whether all the responses are collected or not:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getStatus(){

var d = $.Deferred();

$.post(

"/echo/json/",

{

json: JSON.stringify( {status: Math.floor(Math.random()*4+1)} ),

delay: 1

}

).done(function(s){

d.resolve(s.status);

}).fail(d.reject);

return d.promise();

}

function pollApiCallDone(){

//do something

return getStatus()

.pipe(function(s){

if(s === 1 || s == 2) {

return s;

}

return pollApiCallDone();

});

}

$.blockUI({message: "Please wait while we are Loading the results"});

pollApiCallDone()

.pipe(function(s){

switch(s){

case 1:

return "completed";

case 2:

return "not completed";

}

})

.done(function(s){

$.unblockUI();

alert("The status of collection of API call is >>> " + s);

});

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

Please note that we didn't give any hardcoded value for computing the results, rather we used math.random() to calculate the results every time we hit refresh. This is just a mechanism using which you can pool data, validate it, and then use it as required.

So, we saw how the pipe() method can be beneficial in writing neat and maintainable code. This also gave us a view of how we can use deferred in the longer run while remaining under the umbrella of jQuery.

Joining promises with $.when

$.when is another method that can accept multiple promises and return a master deferred object. This master object can be resolved if all the promises are resolved, or it would be rejected if any of the promises were rejected. You may have sequence likewhen().then().done() or you can add multiple when() methods followed by then() and done().

Let's take a look at an example of how the code will look like with $when():

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getActorByRating(id){

var d = $.Deferred();

$.post(

"/echo/json/",

{json: JSON.stringify({firstName: "Arnold", lastName: "Schwarzenegger", rating: "8.0"})}

).done(function(p){

d.resolve(p);

}).fail(d.reject);

return d.promise();

}

function getActorById(rating){

return $.post("/echo/json/", {

json: JSON.stringify({

rating: "8.0"})

}).pipe(function(p){

return p.rating;

});

}

$.when(getActorByRating(123), getActorById("123456789"))

.done(function(person, rating){

alert("The name is " + person.firstName + " and the rating is " + rating);

});

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

When you execute the preceding code, it will generate an output like this:

Joining promises with $.when

Notice that at the end of the code, the $.when function returns a new master deferred object, and we used two results in one done() callback.

We also changed the getActorByRating() method due to the fact that the promise of an AJAX call, which has the content payload, has the first element in the result along with status code included.

However, this is not the end; you can also use $.when with pipes. Let's see how:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getActor(id){

var d = $.Deferred();

$.post(

"/echo/json/",

{json: JSON.stringify({firstName: "Arnold", lastName: "Schwarzenegger", rating: "8.0"})}

).done(function(p){

d.resolve(p);

}).fail(d.reject);

return d.promise();

}

function getPersonByRating(rating){

return $.post("/echo/json/", {

json: JSON.stringify({

rating: "8.0" })

}).pipe(function(p){

return p.rating;

});

}

$.when(getActor(123), getPersonByRating("123456789"))

.pipe(function(person, rating){

return $.extend(person, {rating: rating});

})

.done(function(person){

alert("The name is " + person.firstName + " and the rating is " + person.rating);

});

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

From the preceding code, you can easily see how when() and pipe() can work in combination and produce results. By summarizing the preceding code, we can say the sequence of our code was like when(), pipe(), and done(). The done() method is the last milestone that has compiled and presented the result on our screen.

We can also use when() as an operator. Remember in JavaScript, every method can be a variable. Let's see how to do it using this code:

<!DOCTYPE html>

<html>

<head>

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

<script>

function getActor(id){

var d = $.Deferred();

$.post(

"/echo/json/",

{json: JSON.stringify({firstName: "Arnold", lastName: "Schwarzenegger", rating: "8.0"}),

delay: 4}

).done(function(p){

d.resolve(p);

}).fail(d.reject);

return d.promise();

}

function getActorByRating(rating){

return $.post("/echo/json/", {

json: JSON.stringify({

rating: "8.0"

}),

delay: 2

}).pipe(function(p){

return p.rating;

});

}

function load(){

$.blockUI({message: "Loading..."});

var loading = getActor(123)

.done(function(c){

$("span#firstName").html(c.firstName)

});

var loadingRating = getActorByRating("8.0")

.done(function(rating){

$("span#rating").html(rating)

});

$.when(loading, loadingRating)

.done($.unblockUI);

}

load();

</script>

</head>

<body>

<h1> you have seen the result . </h1>

</body>

</html>

So from the preceding code, you can clearly see how we can use when() in many different ways. We can add more variety to it as it has many implementations and best case scenarios for solving complex problems.

Your own $.Deferred process

You can customize the deferred object as per your need. This is simple and can be achieved by calling out the jQuery.Deferred() method. We can also define our own process and the sequence of the flow and arrange the output as required. We can usesetInterval() to set up the delays and setTimeout() to decide when to end the sequence. The scope of variable declaration decides whether the deferred object has to be locally or globally processed. If the deferred object is assigned to a local variable, we can call deferred object's resolve(), promise(), and notify() events.

Let's have a look at this example:

var myCustomPromise = process();

myCustomPromise.done(function() {

$('#result').html('done.');

});

myCustomPromise.progress(function() {

$('#result').html($('#result').html() + '.');

});

function process() {

var deferred = $.Deferred();

MyTimerCall = setInterval(function() {

deferred.notify();

}, 1000);

setTimeout(function() {

clearInterval(MyTimerCall);

deferred.resolve();

}, 10000);

return deferred.myCustomPromise();

}

So, from the preceding code, we are able to achieve a skeleton of the processes. This can be simplified by making it more concise or by adding some combining methods such as then(), when(), and so on.

Let's have a look at this compact code:

var MyTimerCall;

(function process() {

$('#result').html('waiting…');

var deferred = $.Deferred();

MyTimerCall = setInterval(function() {

deferred.notify();

}, 1000);

setTimeout(function() {

clearInterval(MyTimerCall);

deferred.resolve();

}, 10000);

return deferred.promise();

})().then(function() { $('#result').html('done.'); },

null,

function() { $('#result').html($('#result').html() + '.'); });

This is more concise and easy to scale. The learning element from this section is one thing; you can also go for the custom-made deferred in jQuery. It's easy, maintainable, and you can scale it as per your need.

The advent of promises in jQuery

So far we learned how promise can be used in jQuery, what deferred object is, and how we can achieve certain tasks using this concept. Why should we use it? The answer is simple, it has many capabilities to maximize our output and build applications in a lesser time. However, what can it actually do for us? Let's have a look.

We can call the done() and fail() functions as many times as we want, with different callbacks. Maybe we have a callback function that can halt our animation, or one that does a new AJAX call, and so on:

var promise = $.ajax({

url: "/echo/"

});

promise.done(StopFadeFunction);

promise.done(FormAjaxFunction);

promise.done(ShowIErrorFunction);

promise.fail(GetErrorFunction);

No matter whether the AJAX call has finished, we can still call the done() and fail() functions and the callbacks are executed immediately. So, variables stated are not a big deal. When the call has finished, it will end up in either the success state or the failed state, and this state will not change.

We can combine promises. Say we have to do two simultaneous AJAX calls and we need to execute a function when both are successfully finished, as shown in the following code:

$.when() function.

var promise1 = $.ajax("/echo1");

var promise2 = $.ajax("/echo2");

$.when(promise1, promise2).done(function(Obj1, Obj2) {

// place object handler here

});

From jQuery 1.8, we can chain the then() function consecutively:

var promiseOne = $.ajax("/echo1");

function getSomthing () {

return $.ajax("/echo2");

}

promiseOne.then(getSomthing).then(function(customeServerScript){

// Both promises are resolved

});

Summary

So, with this chapter coming to an end, let's revise the topics we have covered so far.

We have seen the how jQuery has started taking shape and how it became a fundamental element of the modern-day web development. We have learned how to build basic jQuery documents and how to call the functions embedded into HTML files. We have learned why we started using deferred and promise in jQuery and how it helped us in achieving cutting-edge applications on both web -based platform and portable devices. We have seen saw many working examples to understand better and clear any doubts. The topic of promises in jQuery is huge, but we tried to summarize as much as we can to lay out solid foundations for those who hadn't used this property before and to help those who are already using it.

In the next chapter, we will see how all the combined JavaScript and their properties are shaping up to bring the world closer and making our life easier in the days to come.