SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Último

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Último (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

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.