Learning jQuery Deferreds
Terry Jones
Nicholas H. Tollervey
Preface
The world of JavaScript has changed significantly in recent years withmore sophistication in client-side JavaScript applications and the arrivalof server-side JavaScript using node.js.
In building increasingly complex applications, JavaScript programmers havehad to become more adept at dealing with asynchronous APIs. In earlieryears, JavaScript was all client side. Programmers were only required todeal with single, independent asynchronous function calls, whose resultswere used to update an HTML user interface.
The situation today is far richer. Server-side JavaScript applicationsregularly make multiple asynchronous calls to many other services toproduce responses: to databases, caches, load balancers, the filesystem,authentication systems, third-party APIs, etc. Meanwhile, client-sideJavaScript now has routine access to dozens of asynchronous APIs, such asthose provided by HTML5 as well as good old AJAX (remember, the first A inAJAX stands for asynchronous). Applications need to be able to coordinatesimultaneous calls to multiple asynchronous APIs: to get the fastestresult, to combine information, to wait for multiple calls to complete, toexecute calls in specific orders, to alter the flow of control depending onresults, to deal with errors, to fall back to alternate services (e.g., oncache misses), to retry failing network calls, and so on.
Callback hell, a phrase with about 10,000 Google hits, describes whathappens when programmers try to build modern applications with old-schoolsingle-callback programming. For many programmers, this pain is their dailyreality. Using single callbacks to build applications that need to do evenbasic coordination of asynchronous calls can be very difficult. You have tothink hard and often end up with complicated, brittle, and opaquesolutions. These contain hard-to-find bugs, are hard to document, and canbe very hard to extend when additional asynchronous requirements enter thepicture. Coding for multiple asynchronous events with the single-callbackmodel is a real challenge, even for very smart and experienced programmers.
About You
Firstly, were writing for jQuery programmers who do not know aboutdeferreds. Weve found that most programmers who use jQuery have neverheard of deferreds. Among those who have, there are many who find deferredsconfusing or who are under the false impression that they are too abstractor difficult to understand. Deferreds are a misunderstood yet powerfulprogramming paradigm. Recently, deferreds have been added to manyJavaScript libraries and frameworks, and are now attracting widespreadattention. A search for deferreds onStackOverflow currently gives over 18,000 hits, up 40% in the six monthssince we started this book.
We also want to help JavaScript programmers, both client side and server side , who know about deferreds but arent making heavy use of them. Ifyoud like to beef up your practical knowledge, to see more examples inaction, and to think about deferreds from different angles, wed love tohave you as a reader. We want to help you stretch your mind, in bothbreadth and depth; the book has 18 real-world examples of deferred usealong with 75 challenges (and their solutions) to push your thinking.
Finally, and most ambitiously, we hope weve written a book that will beuseful and stimulating to programmers using deferreds and promises beyondthose in jQuery and even beyond JavaScript. The conceptual underpinningsof deferreds are almost identical across the many JavaScript packages andother programming languages that support them. Because the concepts are sosimilar and so few, youll find it straightforward to port code betweenimplementations. Virtually everything you learn in this book will beuseful for working with other flavors of deferreds. We want it to be a funand valuable read, no matter what your preferred language is. Weve triedto write the book we wish had been available as we learned deferredsourselves.
Our Aims
In this book well teach you how to avoid callback hell by using deferreds.
But theres much more to deferreds than that. Deferreds provide somethingthat was not there before: a simple mechanism for dealing with futureresults. This gives you the opportunity to do things in different ways thatgo beyond mere simplification of syntax. It gives you the opportunity toreally think about the practice of programming and to broaden your mentaltoolkit. The thinking can of course be critical, including conclusionsabout which deferred package to use or whether it is even sensible to usedeferreds in a given situation. For us, the process of learning about andbeginning to appreciate programming with deferreds was a feeling of ourbrains growing new muscles.
Our primary aim is to introduce deferreds to programmers who have had noexposure to them. Were aiming to give you a really strong general andconcrete understanding of what deferreds are and how to wield them. If wesucceed, youll be fully confident when encountering deferreds in any othercontext: whether with another JavaScript deferred package or in a differentprogramming language.
A secondary aim is to provide a broad collection of examples of nontrivialreal-world deferred uses. Weve been programming with deferreds (in Pythonand JavaScript) for the last 7 years and have pulled together some of themost useful examples weve built in that time. These are usually relativelyshort snippets of code, around 100 lines, but sometimes require carefulthought to develop. We hope the detailed recipes in will be a place youll return to for ideas on how to approach deferredproblems you face.
Challenges
The deferred recipes in all leave you with a set ofchallenges. These are meant to encourage you to engage with and think moredeeply about the material just presented. If you want to write code aswell, thats a bonus. The main point, however, is to think . Dont be apassive reader! Working with deferreds very often requires focusedthinking about how problems, and small variations on them, might be solved.Once you get deferreds, solving puzzles with them can be very engaging.The more you do it, the better you get, and the more you see theirflexibility and power. Above all though, figuring out how to do thingswith deferreds is just plain fun!
If youre stuck on a challenge, youll find hints and solutions in.
jQuery Deferreds
We chose to focus on jQuery deferreds because jQuery is ubiquitous andbecause two important and familiar aspects of jQuery ($.ajax
andanimations) already have deferred support built in.
However, jQuery deferreds are certainly not the last word on the subject.As you will see, they differ markedly in one important respect from themany (at least 35) other deferred packages for JavaScript: jQuery deferredsdo not currently follow the excellent ).
This book was written for the .
Our JavaScript Coding Style, or Lack Thereof
JavaScript is not a theres only one way to do it language. As aresult, almost every line of code in the book could have been writtendifferently. To keep the focus on deferreds, weve chosen to write code inthe simplest/clearest possible way. It will be up to you to slightly changeour examples to fit whatever coding style or framework youre using to, forexample, create JavaScript objects (via new
, using self-calling anonymousfunctions, global variables, etc.), loop (for
loop, $.map
, [].forEach
etc.), write variable declarations, log via console.log
, and so on.Also, in the name of keeping the focus on deferreds, we often ignore (oralmost ignore) error processing.