SlideShare una empresa de Scribd logo
1 de 48
Promises & Deferreds
look into the async future
@slicejs
Plan
1. Introduction
2. What problem promises can solve ?
3. Promises in jQuery
Promises are a
programming construct
that have been around
since 1976.
http://en.wikipedia.org/wiki/Futures_and_promises
Brief History of Promises
● Term was first used by C++ engineers on the Xanadu project (1976)
● 2007: Dojo Framework added dojo.Deferred
● 2009: dojo.Deferred influenced Kris Zyp - Proposal of CommonJS
Promises/A spec.
● 2009: Node.js - used Promises in its non blocking API
● 2009: two implementations (Kris Kowal Q.js and O'Neill Futures.js)
● 2011: jQuery rewrites Ajax - ( not 100% CommonJS spec compliant )
20071976 2009 2011
What is a Promise ?
A Promise is an object that represents a task with two
possible outcomes (success or failure)
holds callbacks that fire when one outcome or the
other has occurred
Promises & Deferreds
Promise represents a value that is not yet
known
Deferred represents work that is not yet
finished
CommonJS Promises/A spec
Proposal by Kris Zyp
What's inside ?
The Promises /A Proposal suggests the following standard behavior and API
regardless of implementation details.
A promise has 3 possible states: unfulfilled, fulfilled and failed.
● unfulfilled: since a promise is a proxy for an unknown value it starts in
an unfulfilled state
● fulfilled: the promise is filled with the value it was waiting for
● failed: if the promise was returned an exception, it is in the failed state.
then(
fulfilledHandler,
errorHandler,
progressHandler
);
What's inside
A promise:
● has a function as a value for the property then
(which must return a promise )
● Adds a fulfilledHandler, errorHandler, and progressHandler to be called
for completion of a promise.
● then(fulfilledHandler, errorHandler, progressHandler);
Current implementations
● Kris Kowal’s Q.js
● AJ O'Neal’s FuturesJS
● jQuery since 1.5
Q.js - implementation of the Promises/A spec
Futures - is a broader toolkit, incorporating many of the flow control
features found in libraries like Async.js.
jQuery - not 100% Promises/A compliant.
https://github.com/kriskowal/q
https://github.com/coolaj86/futures
Why do we need
promises ?
sync !== async
But they exist parallely
How do we manage this ?
Anybody ?
We used to use callbacks
A callback is a piece of executable code that is passed as
an argument to other code, which is expected to call back
(execute ) the argument at some convenient time
— Wikipedia
There's nothing wrong
with them
until...
Do you know that ?
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
Such a case - "Taka sytuacja"
● make an Ajax request to get some data
● do something with data, then
● do other things
Insights
● request is made
● execution of our program isn't stopped while the server is responding
● By the time we get the response data from our Ajax request, the
program has already finished execution
Wouldn't be better
doStuff();
that way ?
var $doStuff = $.Deferred();
$doStuff
.done(doOtherStuff)
.fail(keepCalmAndDrinkWine);
doStuff() - easier way
Let's take a closer
look on Deferred
object
then
Deferred
Promise
(A)Handlers States
$.then() $.when()
has
has has
based on
represented by
as unfinished work
as yet unknown value
what to do once work is done
ad value is known
pending = unfulfilled = waiting
fulfilled = resolved = success
rejected = failed = error
hold off doing things until you
have result of doing that
Deferred object
execute callbacks based on one
or more objects that represents
async events
Promise - states & flows
Promise
unfulfilled fulfilled
failed
Promises can help
We can write
asynchronous JavaScript
parallel to how we write
synchronous code
Where to use promises
● Ajax
● Timing tasks (games)
● Synchronizing parallel tasks with $.when()
● Decoupling events and application logic
● Animations
We love jQuery (don't we ?)
Let's take a look at their
implementation
jQuery 1.5 changed Mr. Ajax
since(version1.5) {
$.ajax();
$.get();
$.post();
return Promises;
} that's amazing !
Deferreds team in complete
$.Deferred();
deferred.always();
deferred.then();
deferred.when();
deferred.resolve(); or deferred.reject();
deferred.promise();
deferred.state();
deferred.done();
deferred.fail();
$.ajax();
How to use them ?
Instantiate Deferred
var future = $.Deferred();
$.Deferred()
A constructor that creates a new deferred object.
Accepts an optional init function which will be executed
immediately after the deferred is created.
Place your toys & voila
var step1, step2, url;
url = 'example.json';
step1 = $.ajax(url);
step2 = step1.then(
function (data) {
setTimeout(function () {
console.log('Request completed');
}, 3000);
});
step2.done(function () {
console.log('Sequence completed')
});
});
deferred.then();
Adds handlers which will be called on
● resolved
● rejected or in
● progress
and
returns a promise;
deferred.when();
Returns a new promise based on the completion of
multiple promises.
If any promise is rejected,
.when() is rejected and if all promises are resolved, it is
resolved.
deferred.when();
function taskOne() {
setTimeout(function() {
console.log('task1');
}, 1000);
}
function taskTwo() {
setTimeout(function() {
console.log('task1');
}, 3000);
}
$.when(taskOne, taskTwo).done(function () {
console.log('taskOne and taskTwo are finished');
});
Example
var prompt = $.Deferred();
$('#playGame').focus().on('keypress', function(e) {
var Y = 121, N = 110;
if(e.keyCode === Y) {
prompt.resolve();
} else if (e.keyCode === N) {
prompt.reject();
} else {
return false;
}
});
prompt.always(function(){console.log('A choice was made:');});
prompt.done(function(){ console.log('Starting game...'); });
prompt.fail(function(){ console.log('No game today.'); });
Few things to remember
● callbacks in order in which they were bound
● Promise can be resolved or rejected only once
jQuery vs. CommonJs Promises/A
● implementation are nearly identical
● they use the same words to mean different things
● jQuery uses resolve as opposite of fail
● Promises/A uses fullfill
● jQ 1.8 then method (shorthand done, fail and progress)
● jQ then === pipe (pipe from 1.8+ deprecated)
● noticeable in the case of error handling
Thank you
Code showcase
Discussion
then
Images used in presentation
● Callback mem
http://i.imgur.com/dHCqj.jpg
● Thank you image http://media.tumblr.
com/cda999f9eb5857ea62323368f1a94577/tumblr_inline_misrk5wRf81qz4rgp.gif
● jQuery logo
http://upload.wikimedia.org/wikipedia/en/9/9e/JQuery_logo.svg
● Dojo logo
http://www.socialseomanagement.com/sites/default/files/dojo.png
● Ajax can http://www.walgreens.com/dbimagecache/03500005360_450x450_a.jpg?
01AD=3L88KEUeA9XexrvKpx8FNgPIx6lu4gfXFVidRMbWTJqGPihxbA-
UDiQ&01RI=71DA49E5EE1856F&01NA=
Links from presentation
● CommonJS Promises / A spec
http://wiki.commonjs.org/wiki/Promises/A
http://wiki.commonjs.org/wiki/Promises/A
● Ksis Zyp Github
https://github.com/kriszyp
● Q.js library (github)
https://github.com/kriskowal/q
● Future's js (github)
https://github.com/coolaj86/futures
● jQuery Deferred API
http://api.jquery.com/category/deferred-object/
● Promises libraries perf test
https://github.com/cujojs/promise-perf-tests

Más contenido relacionado

La actualidad más candente

Angular testing
Angular testingAngular testing
Angular testingYu Jin
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt InternationalizationICS
 
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196Mahmoud Samir Fayed
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202Mahmoud Samir Fayed
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The FutureTracy Lee
 
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made EasyLockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made EasyICS
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkZachary Blair
 
QTP Descriptive programming Tutorial
QTP Descriptive programming TutorialQTP Descriptive programming Tutorial
QTP Descriptive programming TutorialJim Orlando
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentICS
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4ICS
 
Raphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React FiberRaphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React FiberReact Conf Brasil
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016Mike Nakhimovich
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Loiane Groner
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Lessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APILessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APIDirk-Jan Rutten
 
How to build your own auto-remediation workflow - Ansible Meetup Munich
How to build your own auto-remediation workflow - Ansible Meetup MunichHow to build your own auto-remediation workflow - Ansible Meetup Munich
How to build your own auto-remediation workflow - Ansible Meetup MunichJürgen Etzlstorfer
 
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...Codemotion
 

La actualidad más candente (20)

Angular testing
Angular testingAngular testing
Angular testing
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made EasyLockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
QTP Descriptive programming Tutorial
QTP Descriptive programming TutorialQTP Descriptive programming Tutorial
QTP Descriptive programming Tutorial
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
Raphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React FiberRaphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React Fiber
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Lessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APILessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL API
 
How to build your own auto-remediation workflow - Ansible Meetup Munich
How to build your own auto-remediation workflow - Ansible Meetup MunichHow to build your own auto-remediation workflow - Ansible Meetup Munich
How to build your own auto-remediation workflow - Ansible Meetup Munich
 
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
 

Similar a Promises look into the async future

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJeff Fox
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
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
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideMek Srunyu Stittri
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
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
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 

Similar a Promises look into the async future (20)

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery Deferred
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
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
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
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
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 

Último

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
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
 
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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
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
 
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
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
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
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 

Último (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
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
 
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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
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
 
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
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
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
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 

Promises look into the async future

  • 1. Promises & Deferreds look into the async future @slicejs
  • 2. Plan 1. Introduction 2. What problem promises can solve ? 3. Promises in jQuery
  • 3. Promises are a programming construct that have been around since 1976. http://en.wikipedia.org/wiki/Futures_and_promises
  • 4. Brief History of Promises ● Term was first used by C++ engineers on the Xanadu project (1976) ● 2007: Dojo Framework added dojo.Deferred ● 2009: dojo.Deferred influenced Kris Zyp - Proposal of CommonJS Promises/A spec. ● 2009: Node.js - used Promises in its non blocking API ● 2009: two implementations (Kris Kowal Q.js and O'Neill Futures.js) ● 2011: jQuery rewrites Ajax - ( not 100% CommonJS spec compliant ) 20071976 2009 2011
  • 5. What is a Promise ? A Promise is an object that represents a task with two possible outcomes (success or failure) holds callbacks that fire when one outcome or the other has occurred
  • 6. Promises & Deferreds Promise represents a value that is not yet known Deferred represents work that is not yet finished
  • 8. What's inside ? The Promises /A Proposal suggests the following standard behavior and API regardless of implementation details. A promise has 3 possible states: unfulfilled, fulfilled and failed. ● unfulfilled: since a promise is a proxy for an unknown value it starts in an unfulfilled state ● fulfilled: the promise is filled with the value it was waiting for ● failed: if the promise was returned an exception, it is in the failed state.
  • 10. What's inside A promise: ● has a function as a value for the property then (which must return a promise ) ● Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise. ● then(fulfilledHandler, errorHandler, progressHandler);
  • 11. Current implementations ● Kris Kowal’s Q.js ● AJ O'Neal’s FuturesJS ● jQuery since 1.5 Q.js - implementation of the Promises/A spec Futures - is a broader toolkit, incorporating many of the flow control features found in libraries like Async.js. jQuery - not 100% Promises/A compliant. https://github.com/kriskowal/q https://github.com/coolaj86/futures
  • 12. Why do we need promises ?
  • 14. But they exist parallely
  • 15. How do we manage this ?
  • 17. We used to use callbacks A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute ) the argument at some convenient time — Wikipedia
  • 18. There's nothing wrong with them until...
  • 19. Do you know that ? step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); });
  • 20.
  • 21. Such a case - "Taka sytuacja" ● make an Ajax request to get some data ● do something with data, then ● do other things
  • 22. Insights ● request is made ● execution of our program isn't stopped while the server is responding ● By the time we get the response data from our Ajax request, the program has already finished execution
  • 24. var $doStuff = $.Deferred(); $doStuff .done(doOtherStuff) .fail(keepCalmAndDrinkWine); doStuff() - easier way
  • 25. Let's take a closer look on Deferred object then
  • 26. Deferred Promise (A)Handlers States $.then() $.when() has has has based on represented by as unfinished work as yet unknown value what to do once work is done ad value is known pending = unfulfilled = waiting fulfilled = resolved = success rejected = failed = error hold off doing things until you have result of doing that Deferred object execute callbacks based on one or more objects that represents async events
  • 27. Promise - states & flows Promise unfulfilled fulfilled failed
  • 29. We can write asynchronous JavaScript parallel to how we write synchronous code
  • 30. Where to use promises ● Ajax ● Timing tasks (games) ● Synchronizing parallel tasks with $.when() ● Decoupling events and application logic ● Animations
  • 31. We love jQuery (don't we ?) Let's take a look at their implementation
  • 32. jQuery 1.5 changed Mr. Ajax since(version1.5) { $.ajax(); $.get(); $.post(); return Promises; } that's amazing !
  • 33. Deferreds team in complete $.Deferred(); deferred.always(); deferred.then(); deferred.when(); deferred.resolve(); or deferred.reject(); deferred.promise(); deferred.state(); deferred.done(); deferred.fail(); $.ajax();
  • 34. How to use them ?
  • 36. $.Deferred() A constructor that creates a new deferred object. Accepts an optional init function which will be executed immediately after the deferred is created.
  • 37. Place your toys & voila var step1, step2, url; url = 'example.json'; step1 = $.ajax(url); step2 = step1.then( function (data) { setTimeout(function () { console.log('Request completed'); }, 3000); }); step2.done(function () { console.log('Sequence completed') }); });
  • 38. deferred.then(); Adds handlers which will be called on ● resolved ● rejected or in ● progress and returns a promise;
  • 39. deferred.when(); Returns a new promise based on the completion of multiple promises. If any promise is rejected, .when() is rejected and if all promises are resolved, it is resolved.
  • 40. deferred.when(); function taskOne() { setTimeout(function() { console.log('task1'); }, 1000); } function taskTwo() { setTimeout(function() { console.log('task1'); }, 3000); } $.when(taskOne, taskTwo).done(function () { console.log('taskOne and taskTwo are finished'); });
  • 41. Example var prompt = $.Deferred(); $('#playGame').focus().on('keypress', function(e) { var Y = 121, N = 110; if(e.keyCode === Y) { prompt.resolve(); } else if (e.keyCode === N) { prompt.reject(); } else { return false; } }); prompt.always(function(){console.log('A choice was made:');}); prompt.done(function(){ console.log('Starting game...'); }); prompt.fail(function(){ console.log('No game today.'); });
  • 42. Few things to remember ● callbacks in order in which they were bound ● Promise can be resolved or rejected only once
  • 43. jQuery vs. CommonJs Promises/A ● implementation are nearly identical ● they use the same words to mean different things ● jQuery uses resolve as opposite of fail ● Promises/A uses fullfill ● jQ 1.8 then method (shorthand done, fail and progress) ● jQ then === pipe (pipe from 1.8+ deprecated) ● noticeable in the case of error handling
  • 47. Images used in presentation ● Callback mem http://i.imgur.com/dHCqj.jpg ● Thank you image http://media.tumblr. com/cda999f9eb5857ea62323368f1a94577/tumblr_inline_misrk5wRf81qz4rgp.gif ● jQuery logo http://upload.wikimedia.org/wikipedia/en/9/9e/JQuery_logo.svg ● Dojo logo http://www.socialseomanagement.com/sites/default/files/dojo.png ● Ajax can http://www.walgreens.com/dbimagecache/03500005360_450x450_a.jpg? 01AD=3L88KEUeA9XexrvKpx8FNgPIx6lu4gfXFVidRMbWTJqGPihxbA- UDiQ&01RI=71DA49E5EE1856F&01NA=
  • 48. Links from presentation ● CommonJS Promises / A spec http://wiki.commonjs.org/wiki/Promises/A http://wiki.commonjs.org/wiki/Promises/A ● Ksis Zyp Github https://github.com/kriszyp ● Q.js library (github) https://github.com/kriskowal/q ● Future's js (github) https://github.com/coolaj86/futures ● jQuery Deferred API http://api.jquery.com/category/deferred-object/ ● Promises libraries perf test https://github.com/cujojs/promise-perf-tests