SlideShare a Scribd company logo
1 of 33
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

More Related Content

What's hot

React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit TestingEswara Kumar Palakollu
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and ReduxThom Nichols
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptMathieu Savy
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with ReduxStephan Schmidt
 
Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with ReduxFernando Daciuk
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In MeteorDesignveloper
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developerEugene Zharkov
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with ReduxMaurice De Beijer [MVP]
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React NativeEric Deng
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & ReduxBoris Dinkevich
 

What's hot (20)

Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit Testing
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScript
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
 
Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with Redux
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In Meteor
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developer
 
React js
React jsReact js
React js
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
 
Redux js
Redux jsRedux js
Redux js
 
React js
React jsReact js
React js
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
 

Viewers also liked

Json at work overview and ecosystem-v2.1
Json at work   overview and ecosystem-v2.1Json at work   overview and ecosystem-v2.1
Json at work overview and ecosystem-v2.1Tom Marrs
 
When You Are Angry
When You Are AngryWhen You Are Angry
When You Are AngrySukh Sandhu
 
Qualified Social Media Expert
Qualified Social Media ExpertQualified Social Media Expert
Qualified Social Media ExpertSukh Sandhu
 
JSON Part 2: Working with Ajax
JSON Part 2: Working with AjaxJSON Part 2: Working with Ajax
JSON Part 2: Working with AjaxJeff Fox
 
Dynamic webpages using AJAX & JSON
Dynamic webpages using AJAX & JSONDynamic webpages using AJAX & JSON
Dynamic webpages using AJAX & JSONChristiaan Rakowski
 
Data Intechange at Work: XML and JSON
Data Intechange at Work: XML and JSONData Intechange at Work: XML and JSON
Data Intechange at Work: XML and JSONTom Marrs
 
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Adnan Sohail
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webkriszyp
 
Security problems in TCP/IP
Security problems in TCP/IPSecurity problems in TCP/IP
Security problems in TCP/IPSukh Sandhu
 
External Data Access with jQuery
External Data Access with jQueryExternal Data Access with jQuery
External Data Access with jQueryDoncho Minkov
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 

Viewers also liked (20)

Json
JsonJson
Json
 
Json at work overview and ecosystem-v2.1
Json at work   overview and ecosystem-v2.1Json at work   overview and ecosystem-v2.1
Json at work overview and ecosystem-v2.1
 
When You Are Angry
When You Are AngryWhen You Are Angry
When You Are Angry
 
Qualified Social Media Expert
Qualified Social Media ExpertQualified Social Media Expert
Qualified Social Media Expert
 
JSON Part 2: Working with Ajax
JSON Part 2: Working with AjaxJSON Part 2: Working with Ajax
JSON Part 2: Working with Ajax
 
Dynamic webpages using AJAX & JSON
Dynamic webpages using AJAX & JSONDynamic webpages using AJAX & JSON
Dynamic webpages using AJAX & JSON
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
 
Data Intechange at Work: XML and JSON
Data Intechange at Work: XML and JSONData Intechange at Work: XML and JSON
Data Intechange at Work: XML and JSON
 
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)
 
Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAX
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the web
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Security problems in TCP/IP
Security problems in TCP/IPSecurity problems in TCP/IP
Security problems in TCP/IP
 
Introduction to Advanced Javascript
Introduction to Advanced JavascriptIntroduction to Advanced Javascript
Introduction to Advanced Javascript
 
Json tutorial
Json tutorialJson tutorial
Json tutorial
 
Json
JsonJson
Json
 
External Data Access with jQuery
External Data Access with jQueryExternal Data Access with jQuery
External Data Access with jQuery
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuery
 

Similar to JSON Part 3: Asynchronous Ajax & JQuery Deferred

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware ArchitectureMateusz Bosek
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to ReactJean Carlo Emer
 
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011Mobicents JSLEE progress and roadmap - Mobicents Summit 2011
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011telestax
 
Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022David Gómez García
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 

Similar to JSON Part 3: Asynchronous Ajax & JQuery Deferred (20)

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011Mobicents JSLEE progress and roadmap - Mobicents Summit 2011
Mobicents JSLEE progress and roadmap - Mobicents Summit 2011
 
Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022
 
Ajax
AjaxAjax
Ajax
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 

JSON Part 3: Asynchronous Ajax & JQuery Deferred

  • 1. BUILT IN FAIRFIELD COUNTY: 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 Ajax Review Asynchronous operations The Deferred Pattern Using Deferred with JQuery Live Demo Final Wrap Up
  • 4. JSON and Ajax Review
  • 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. 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
  • 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. Examples of Asynchronous operations Function Callbacks Animations Polling External Data Calls (Ajax) User Events
  • 10. The Deferred Pattern and Promises/A
  • 11. No…Not that kind of pattern
  • 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. 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
  • 15. Old method for handling Ajax Requests $.ajax({ url: "/aphppage.php", success: function() { // handle success }, error: function() { // handle error });
  • 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. 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. 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. 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. 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 Multiple callbacks can be assigned to Deferred objects Callbacks are executed in the order they were added.
  • 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. 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. Simple Then example when( promise1, promise2, ... ).then(function( futureValue1, futureValue2, ... ){ /* all promises have completed successfully */ }, function(){ /* error(s) occurred*/ });
  • 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
  • 28. Demos Simple static Deferred execution examples Deferred object applied to Dynamic App demo Combining multiple Ajax calls with when() and then()
  • 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. 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. 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.