BUILT IN FAIRFIELD COUNTY:
FRONT END DEVELOPERS MEETUP
TUES. JULY 9, 2013
JSON Part 3:
Asynchronous Ajax and JQuery Deferred
About Jeff Fox (@jfox015)
16 year web development professional
(Almost) entirely self taught
Thorough front and back end experience
Develops JavaScript based web apps that rely
on JSON and Ajax for data workflow
Overview
JSON and Ajax Review
Asynchronous operations
The Deferred Pattern
Using Deferred with JQuery
Live Demo
Final Wrap Up
JSON and Ajax Review
JSON Highlights
A lightweight text based data interchange format
Use it to transfer JavaScript object data to and from a
remote data source
Language independent
Based on a subset of the JavaScript Programming
Language
Easy to understand, manipulate and generate
Ajax Highlights
Ajax is “Asynchronous JavaScript and XML”
JavaScript API for exchanging data with a web server and
returning the response to JavaScript
First created by Microsoft before being standardized by the
open source community and W3C
Faster data exchange than sending and loading full web
pages
Can either make for a better user experience or hinder it
Onto Asynchronous
operations
Asynchronous operations are…
Operations that occur without a regular or predictable
time relationship to a specified event such as a mouse
click or time interval
Often times unpredictable
when used on the Web
Linear functions within a script
will may be executed even
before the Ajax operation has
responded
Examples of Asynchronous operations
Function Callbacks
Animations
Polling
External Data Calls (Ajax)
User Events
The Deferred Pattern and
Promises/A
No…Not that kind of pattern
The Deferred Design Pattern
Describes an object which acts as a proxy for a process or
action that may or may not have completed
Can be applied to any asynchronous process such as AJAX
requests, scripted animations, or web workers
Allows you to specify what will occur when the delayed
process either completes or fails
Helps to abstract away the "when" part of your
asynchronous processes
Promises/A
A open spec created to simply detail the expected
functionality of then() functions.
A guide for developers and JS lib creators to build
common and cohesive then() support
JQuery 1.9.1 currently does not provide full support for
this spec as written
Using Deferred with JQuery
Old method for handling Ajax Requests
$.ajax({
url: "/aphppage.php",
success: function() { // handle
success },
error: function() { // handle
error });
The JQuery Deferred object
Allows multiple listeners to Ajax events without manually
chaining callbacks
Can be manually created via the $.Deferred() method
Can register callback functions if deferred resolves successfully,
is rejected or notify of progress towards a resolved state
Can be passed around indefinitely
Callbacks can continue to be added during the entire lifetime of
the deferred object, even if it is in a resolved state
More JQuery Deferred
Starts out in a Pending state. Can only be resolved once in
lifecycle.
Calls all listeners immediately (albeit asynchronously) once it is
resolved.
Will execute any new callbacks immediately if it is resolved.
Ajax Resolution and Rejection
JQuery's ajax() method will call resolve() on the deferred
it returns when the request completes successfully, and
reject() if the request fails (for example, a 404 HTTP
response).
resolve() and reject() can also be manually executed on
any manually created Deferred object
The JQuery Deferred Promise
A Promise is a read-only JQuery
Deferred object
These are returned by default by
all JQuery Ajax methods
They give us back functional composition and error
bubbling in the asynchronous world
Handling completed promises
done() is the default callback for handling a successful
Ajax operation
$.get(url)
.done(function(){ alert(“Operation done.”); });
fail() is the default handler for operations that are
rejected.
$.get(url)
.done(function(){ alert(“Operation done.”); })
.fail(function(){ alert(“Operation failed.”); });
Handling completed promises
always() executed regardless of whether done or fail are
completed
$.get(“someurl.php”)
.done(function(){ alert(“Operation done.”); })
.fail(function(){ alert(“Operation failed.”); })
.always(function() { alert(“Operations complete.”});
Handling completed promises
Multiple callbacks can be assigned to Deferred
objects
Callbacks are executed in the order they were
added.
Handling multiple deferred operations
$.when() accepts one or more promises and produces a
new promise that will only resolve when all the supplied
objects have completed or failed
If a single argument is passed that is not a Deferred or
Promise, it will be treated as a resolved Deferred and any
callbacks will be executed immediately
var emp_def = $.get(“employees”),
loc_def = $.get(“locations”);
$.when(emp_def, loc_def)
.done(function(emp_resp, loc_resp){ alert(“Operations
done.”); });
Handling multiple deferred operations
$.then() adds handlers to be called when the Deferred
object is resolved, rejected, or still in progress.
As of JQuery 1.8, returns a new promise that can filter
the status and values of a deferred through a function
Replaces the deprecated pipe() function
Simple Then example
when(
promise1,
promise2,
...
).then(function( futureValue1,
futureValue2, ... ){
/* all promises have completed successfully
*/
}, function(){
/* error(s) occurred*/
});
Notifying Deferred Objects
JQuery 1.7+ includes the concept of progress to a
deferred
progress() allows you to attach callbacks that are
executed when notify() is called on the deferred
This allows the deferred to represent the concept of
progress towards a resolved state
Can be attached to long loading processes to update a
progress bar, for example
Live Examples
Demos
Simple static Deferred execution examples
Deferred object applied to Dynamic App demo
Combining multiple Ajax calls with when() and then()
Resources
JQuery Deferred API Spec:
http://api.jquery.com/category/deferred-object/
An introduction to JQuery Deferred by Daniel Demmel
http://danieldemmel.me/blog/2013/03/22/an-
introduction-to-jquery-deferred-slash-promise/
Download Example Code:
https://github.com/jfox015/BIFC-JSON-Deferred
Resources
You're Missing the Point of Promises by Domenic
Denicola
http://domenic.me/2012/10/14/youre-missing-the-
point-of-promises/
Making Promises With JQuery Deferred
http://www.htmlgoodies.com/beyond/javascript/making
-promises-with-jquery-deferred.html
Image Pre-loader using Deferred Object:
https://gist.github.com/fcalderan/958683
Resources
JS Libs with Promises/A support:
 Q by Kris Kowal and Domenic Denicola: a full-featured promise
library with a large, powerful API surface, adapters for Node.js,
progress support, and preliminary support for long stack traces.
 RSVP.js by Yehuda Katz: a very small and lightweight, but still fully
compliant, promise library.
 when.js by Brian Cavalier: an intermediate library with utilities for
managing collections of eventual tasks, as well as support for both
progress and cancellation.
Questions?
JSON Part 3: Asynchronous Ajax & JQuery Deferred

JSON Part 3: Asynchronous Ajax & JQuery Deferred

  • 1.
    BUILT IN FAIRFIELDCOUNTY: FRONT END DEVELOPERS MEETUP TUES. JULY 9, 2013 JSON Part 3: Asynchronous Ajax and JQuery Deferred
  • 2.
    About Jeff Fox(@jfox015) 16 year web development professional (Almost) entirely self taught Thorough front and back end experience Develops JavaScript based web apps that rely on JSON and Ajax for data workflow
  • 3.
    Overview JSON and AjaxReview Asynchronous operations The Deferred Pattern Using Deferred with JQuery Live Demo Final Wrap Up
  • 4.
  • 5.
    JSON Highlights A lightweighttext based data interchange format Use it to transfer JavaScript object data to and from a remote data source Language independent Based on a subset of the JavaScript Programming Language Easy to understand, manipulate and generate
  • 6.
    Ajax Highlights Ajax is“Asynchronous JavaScript and XML” JavaScript API for exchanging data with a web server and returning the response to JavaScript First created by Microsoft before being standardized by the open source community and W3C Faster data exchange than sending and loading full web pages Can either make for a better user experience or hinder it
  • 7.
  • 8.
    Asynchronous operations are… Operationsthat occur without a regular or predictable time relationship to a specified event such as a mouse click or time interval Often times unpredictable when used on the Web Linear functions within a script will may be executed even before the Ajax operation has responded
  • 9.
    Examples of Asynchronousoperations Function Callbacks Animations Polling External Data Calls (Ajax) User Events
  • 10.
    The Deferred Patternand Promises/A
  • 11.
  • 12.
    The Deferred DesignPattern Describes an object which acts as a proxy for a process or action that may or may not have completed Can be applied to any asynchronous process such as AJAX requests, scripted animations, or web workers Allows you to specify what will occur when the delayed process either completes or fails Helps to abstract away the "when" part of your asynchronous processes
  • 13.
    Promises/A A open speccreated to simply detail the expected functionality of then() functions. A guide for developers and JS lib creators to build common and cohesive then() support JQuery 1.9.1 currently does not provide full support for this spec as written
  • 14.
  • 15.
    Old method forhandling Ajax Requests $.ajax({ url: "/aphppage.php", success: function() { // handle success }, error: function() { // handle error });
  • 16.
    The JQuery Deferredobject Allows multiple listeners to Ajax events without manually chaining callbacks Can be manually created via the $.Deferred() method Can register callback functions if deferred resolves successfully, is rejected or notify of progress towards a resolved state Can be passed around indefinitely Callbacks can continue to be added during the entire lifetime of the deferred object, even if it is in a resolved state
  • 17.
    More JQuery Deferred Startsout in a Pending state. Can only be resolved once in lifecycle. Calls all listeners immediately (albeit asynchronously) once it is resolved. Will execute any new callbacks immediately if it is resolved.
  • 18.
    Ajax Resolution andRejection JQuery's ajax() method will call resolve() on the deferred it returns when the request completes successfully, and reject() if the request fails (for example, a 404 HTTP response). resolve() and reject() can also be manually executed on any manually created Deferred object
  • 19.
    The JQuery DeferredPromise A Promise is a read-only JQuery Deferred object These are returned by default by all JQuery Ajax methods They give us back functional composition and error bubbling in the asynchronous world
  • 20.
    Handling completed promises done()is the default callback for handling a successful Ajax operation $.get(url) .done(function(){ alert(“Operation done.”); }); fail() is the default handler for operations that are rejected. $.get(url) .done(function(){ alert(“Operation done.”); }) .fail(function(){ alert(“Operation failed.”); });
  • 21.
    Handling completed promises always()executed regardless of whether done or fail are completed $.get(“someurl.php”) .done(function(){ alert(“Operation done.”); }) .fail(function(){ alert(“Operation failed.”); }) .always(function() { alert(“Operations complete.”});
  • 22.
    Handling completed promises Multiplecallbacks can be assigned to Deferred objects Callbacks are executed in the order they were added.
  • 23.
    Handling multiple deferredoperations $.when() accepts one or more promises and produces a new promise that will only resolve when all the supplied objects have completed or failed If a single argument is passed that is not a Deferred or Promise, it will be treated as a resolved Deferred and any callbacks will be executed immediately var emp_def = $.get(“employees”), loc_def = $.get(“locations”); $.when(emp_def, loc_def) .done(function(emp_resp, loc_resp){ alert(“Operations done.”); });
  • 24.
    Handling multiple deferredoperations $.then() adds handlers to be called when the Deferred object is resolved, rejected, or still in progress. As of JQuery 1.8, returns a new promise that can filter the status and values of a deferred through a function Replaces the deprecated pipe() function
  • 25.
    Simple Then example when( promise1, promise2, ... ).then(function(futureValue1, futureValue2, ... ){ /* all promises have completed successfully */ }, function(){ /* error(s) occurred*/ });
  • 26.
    Notifying Deferred Objects JQuery1.7+ includes the concept of progress to a deferred progress() allows you to attach callbacks that are executed when notify() is called on the deferred This allows the deferred to represent the concept of progress towards a resolved state Can be attached to long loading processes to update a progress bar, for example
  • 27.
  • 28.
    Demos Simple static Deferredexecution examples Deferred object applied to Dynamic App demo Combining multiple Ajax calls with when() and then()
  • 29.
    Resources JQuery Deferred APISpec: http://api.jquery.com/category/deferred-object/ An introduction to JQuery Deferred by Daniel Demmel http://danieldemmel.me/blog/2013/03/22/an- introduction-to-jquery-deferred-slash-promise/ Download Example Code: https://github.com/jfox015/BIFC-JSON-Deferred
  • 30.
    Resources You're Missing thePoint of Promises by Domenic Denicola http://domenic.me/2012/10/14/youre-missing-the- point-of-promises/ Making Promises With JQuery Deferred http://www.htmlgoodies.com/beyond/javascript/making -promises-with-jquery-deferred.html Image Pre-loader using Deferred Object: https://gist.github.com/fcalderan/958683
  • 31.
    Resources JS Libs withPromises/A support:  Q by Kris Kowal and Domenic Denicola: a full-featured promise library with a large, powerful API surface, adapters for Node.js, progress support, and preliminary support for long stack traces.  RSVP.js by Yehuda Katz: a very small and lightweight, but still fully compliant, promise library.  when.js by Brian Cavalier: an intermediate library with utilities for managing collections of eventual tasks, as well as support for both progress and cancellation.
  • 32.