JSON Part 3: Asynchronous Ajax & JQuery Deferred


Published on

The final slides from the BFIC Deep Dive into JSON series. This deck covers an introduction to asynchronous operations and how to handle them using the JQuery Deferred object.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

JSON Part 3: Asynchronous Ajax & JQuery Deferred

  1. 1. BUILT IN FAIRFIELD COUNTY: FRONT END DEVELOPERS MEETUP TUES. JULY 9, 2013 JSON Part 3: Asynchronous Ajax and JQuery Deferred
  2. 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. 3. Overview JSON and Ajax Review Asynchronous operations The Deferred Pattern Using Deferred with JQuery Live Demo Final Wrap Up
  4. 4. JSON and Ajax Review
  5. 5. 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
  6. 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. 7. Onto Asynchronous operations
  8. 8. 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
  9. 9. Examples of Asynchronous operations Function Callbacks Animations Polling External Data Calls (Ajax) User Events
  10. 10. The Deferred Pattern and Promises/A
  11. 11. No…Not that kind of pattern
  12. 12. 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
  13. 13. 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
  14. 14. Using Deferred with JQuery
  15. 15. Old method for handling Ajax Requests $.ajax({ url: "/aphppage.php", success: function() { // handle success }, error: function() { // handle error });
  16. 16. 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
  17. 17. 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.
  18. 18. 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
  19. 19. 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
  20. 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. 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. 22. Handling completed promises Multiple callbacks can be assigned to Deferred objects Callbacks are executed in the order they were added.
  23. 23. 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.”); });
  24. 24. 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
  25. 25. Simple Then example when( promise1, promise2, ... ).then(function( futureValue1, futureValue2, ... ){ /* all promises have completed successfully */ }, function(){ /* error(s) occurred*/ });
  26. 26. 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
  27. 27. Live Examples
  28. 28. Demos Simple static Deferred execution examples Deferred object applied to Dynamic App demo Combining multiple Ajax calls with when() and then()
  29. 29. 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
  30. 30. 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
  31. 31. 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.
  32. 32. Questions?