SlideShare a Scribd company logo
1 of 32
JavaScript Promises
Pulak (@pulakb)
http://pulakonline.com/
Discussions
• Callbacks
• JavaScript Promises
– jQuery
– ‘q’ library
– AngularJs
– Node.js
• What is a Callback function?
• How Callback function work?
• ‘Callback hell’
What is a Callback function?
• A callback function (say, Y) is a function that is passed to another function
(say, X) as a parameter, and Y gets executed inside X.
• JavaScript uses callback functions to handle asynchronous control flow.
1
2
3
$( "#dataRow" ).on( "click", function() {
alert(‘hello’);
});
How Callback function work?
function writeCode(callback) {
//do something
callback();
//…..
}
function introduceBugs() {
//…. Make bugs
}
writeCode(introduceBugs)
How Callback function work?
fs = require('fs');
fs.readFile ('f1.txt','utf8',function(err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
How Callback function work?
fs = require('fs');
fs.readFile('f1.txt','utf8',function(err,data){
if (err) {
return console.log(err);
}
console.log(data);
});
How Callback function work?
fs = require('fs');
fs.readFile('f1.txt','utf8',
function(err,data){
if (err) {
return console.log(err);
}
console.log(data);
}
);
Equivalent
formatting
‘Callback hell’
• Code complexity
• Modularity
• Maintainability
• Tightly coupled interface
‘Callback hell’
When working with callbacks, nesting of functions can make reading
and understanding the code very difficult
Promises
• What is Promise?
• What is Deferred?
• Deferred & Promise
• What are the use cases of Promise?
• What does Promises guarantee?
• Why promises are awesome?
What is Promise?
• A promise is an object that represents the return value or the
thrown exception that the function may eventually provide.
• In other words, a promise represents a value that is not yet known.
A promise is an asynchronous value.
• The core idea behind promises is that a promise represents the
result of an asynchronous operation.
• A Promise has 3 possible states
– Pending
– Fulfilled
– Rejected
Deferred & Promise
• A deferred (object) represents a work that is not yet finished.
• A promise (property) is a placeholder for a result which is initially
unknown.
• Every deferred has a promise which functions as a proxy for the future
result.
• From a semantic perspective this means that instead of calling a function
( callback ), we are able to return a value ( promise ).
What are the use cases of Promise?
• An AJAX request and callbacks(a single request, parallel/chained requests)
• An asynchronous loading of assets and actions to perform
• Animation
• Modal User Interaction
What does Promise guarantee?
promiseForResult.then(onFulfilled, onRejected);
• Only one of onFulfilled or onRejected will be called.
• onFulfilled will be called with a single fulfillment value (⇔ return value).
• onRejected will be called with a single rejection reason (⇔ thrown
exception).
• If the promise is already settled, the handlers will still be called once you
attach them.
• The handlers will always be called asynchronously.
What does Promise guarantee?
• At first, a Promise is in a pending state. Eventually, it’s either resolved or
rejected.
• Once a Promise is resolved or rejected, it’ll remain in that state forever,
and its callbacks will never fire again
• Promises can be chained
Why promises are awesome
• Cleaner method signatures
• Uniform return/error semantics
• Easy composition
• Easy sequential/parallel join
• Always async
• Exception-style error bubbling
Case 1: Simple Functional Transform
var author = getAuthors();
var authorName = author.name;
// becomes
var authorPromise = getAuthors().then(function (author) {
return author.name;
});
Case 2: Reacting with an Exception
var author = getAuthors();
if (author === null)
throw new Error("null author!");
becomes
var authorPromise = getAuthors().then(function (author) {
if (author === null)
throw new Error("null author!");
return author;
});
Case 3: Handling an Exception
try {
updateAuthor(data);
} catch (ex) {
console.log("There was an error:", ex);
}
// becomes
var updatePromise = updateAuthor(data).then(undefined, function (ex) {
console.log("There was an error:", ex);
});
Case 4: Rethrowing an Exception
try {
updateAuthor(data);
} catch (ex) {
throw new Error("Updating author failed. Details: " + ex.message);
}
// becomes
var updatePromise = updateAuthor(data).then(undefined, function (ex) {
throw new Error("Updating author failed. Details: " + ex.message);
});
Async Case: Waiting
var name = promptForNewAuthorName();
updateAuthor({ name: name });
refreshScreen();
// becomes
promptForNewAuthorName()
.then(function (name) {
return updateAuthor({ name: name });
})
.then(refreshScreen);
jQuery
Q - library
Q - library
jQuery - q differences
• https://github.com/kriskowal/q/wiki/Coming-from-jQuery
jQuery Q Notes
then then
Q's then, and in fact all of its methods, have
different exception-handling behavior, as described
above.
done then
then does not support multiple handlers; use
multiple calls to then to attach them.
fail catch
catch does not support multiple handlers; use
multiple calls to catch to attach them.
deferred.promise(method) deferred.promise(property)
You *must* get the promise part of the deferred;
the deferred does not have the promise API.
Node and q library
AngularJS
AngularJS
– Limitations of Promise in Angular
In Angular's $Q implementation, If you don't fire off $scope.$apply(),
after resolving, the resolved values will never propagate to your 'then'
functions. Sometimes I want to use promises that aren't tied to my
Angular $digest cycle.
URLs
Credit goes to all the people for sharing their thoughts:
• http://wiki.commonjs.org/wiki/Promises/A
• http://promisesaplus.com/
• http://promisesaplus.com/differences-from-promises-a
• http://api.jquery.com/category/deferred-object/
• http://sitr.us/2012/07/31/promise-pipelines-in-javascript.html
• http://stackoverflow.com/questions/12160785/jquery-deferred-promise-design-patterns-and-use-cases
• http://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript
• http://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done
• http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics
• https://gist.github.com/domenic/3889970
• http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
• https://github.com/kriskowal/q
• https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md
• http://james.padolsey.com/jquery/#v=2.0.3&fn=jQuery.Deferred
• http://www.dwmkerr.com/promises-in-angularjs-the-definitive-guide/
• http://spion.github.io/posts/why-i-am-switching-to-promises.html
• http://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/
Q &A

More Related Content

What's hot

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/AwaitValeri Karpov
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validationMaitree Patel
 

What's hot (20)

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Jquery
JqueryJquery
Jquery
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Javascript
JavascriptJavascript
Javascript
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 

Viewers also liked

Viewers also liked (13)

Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Cloud Platform as a Service: Heroku
Cloud Platform as a Service: HerokuCloud Platform as a Service: Heroku
Cloud Platform as a Service: Heroku
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Pragmatics
PragmaticsPragmatics
Pragmatics
 
Speech acts
Speech actsSpeech acts
Speech acts
 
Speech acts
Speech actsSpeech acts
Speech acts
 

Similar to JavaScript Promises Simplified

The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
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
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
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
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-Ievgenii Katsan
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiRobert Nyman
 

Similar to JavaScript Promises Simplified (20)

The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
You promise?
You promise?You promise?
You promise?
 
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
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
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
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, Helsinki
 

Recently uploaded

Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationMarko4394
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 

Recently uploaded (20)

Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentation
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 

JavaScript Promises Simplified

  • 2. Discussions • Callbacks • JavaScript Promises – jQuery – ‘q’ library – AngularJs – Node.js
  • 3. • What is a Callback function? • How Callback function work? • ‘Callback hell’
  • 4. What is a Callback function? • A callback function (say, Y) is a function that is passed to another function (say, X) as a parameter, and Y gets executed inside X. • JavaScript uses callback functions to handle asynchronous control flow. 1 2 3 $( "#dataRow" ).on( "click", function() { alert(‘hello’); });
  • 5. How Callback function work? function writeCode(callback) { //do something callback(); //….. } function introduceBugs() { //…. Make bugs } writeCode(introduceBugs)
  • 6. How Callback function work? fs = require('fs'); fs.readFile ('f1.txt','utf8',function(err,data) { if (err) { return console.log(err); } console.log(data); });
  • 7. How Callback function work? fs = require('fs'); fs.readFile('f1.txt','utf8',function(err,data){ if (err) { return console.log(err); } console.log(data); });
  • 8. How Callback function work? fs = require('fs'); fs.readFile('f1.txt','utf8', function(err,data){ if (err) { return console.log(err); } console.log(data); } ); Equivalent formatting
  • 9. ‘Callback hell’ • Code complexity • Modularity • Maintainability • Tightly coupled interface
  • 10. ‘Callback hell’ When working with callbacks, nesting of functions can make reading and understanding the code very difficult
  • 11. Promises • What is Promise? • What is Deferred? • Deferred & Promise • What are the use cases of Promise? • What does Promises guarantee? • Why promises are awesome?
  • 12. What is Promise? • A promise is an object that represents the return value or the thrown exception that the function may eventually provide. • In other words, a promise represents a value that is not yet known. A promise is an asynchronous value. • The core idea behind promises is that a promise represents the result of an asynchronous operation. • A Promise has 3 possible states – Pending – Fulfilled – Rejected
  • 13. Deferred & Promise • A deferred (object) represents a work that is not yet finished. • A promise (property) is a placeholder for a result which is initially unknown. • Every deferred has a promise which functions as a proxy for the future result. • From a semantic perspective this means that instead of calling a function ( callback ), we are able to return a value ( promise ).
  • 14.
  • 15. What are the use cases of Promise? • An AJAX request and callbacks(a single request, parallel/chained requests) • An asynchronous loading of assets and actions to perform • Animation • Modal User Interaction
  • 16. What does Promise guarantee? promiseForResult.then(onFulfilled, onRejected); • Only one of onFulfilled or onRejected will be called. • onFulfilled will be called with a single fulfillment value (⇔ return value). • onRejected will be called with a single rejection reason (⇔ thrown exception). • If the promise is already settled, the handlers will still be called once you attach them. • The handlers will always be called asynchronously.
  • 17. What does Promise guarantee? • At first, a Promise is in a pending state. Eventually, it’s either resolved or rejected. • Once a Promise is resolved or rejected, it’ll remain in that state forever, and its callbacks will never fire again • Promises can be chained
  • 18. Why promises are awesome • Cleaner method signatures • Uniform return/error semantics • Easy composition • Easy sequential/parallel join • Always async • Exception-style error bubbling
  • 19. Case 1: Simple Functional Transform var author = getAuthors(); var authorName = author.name; // becomes var authorPromise = getAuthors().then(function (author) { return author.name; });
  • 20. Case 2: Reacting with an Exception var author = getAuthors(); if (author === null) throw new Error("null author!"); becomes var authorPromise = getAuthors().then(function (author) { if (author === null) throw new Error("null author!"); return author; });
  • 21. Case 3: Handling an Exception try { updateAuthor(data); } catch (ex) { console.log("There was an error:", ex); } // becomes var updatePromise = updateAuthor(data).then(undefined, function (ex) { console.log("There was an error:", ex); });
  • 22. Case 4: Rethrowing an Exception try { updateAuthor(data); } catch (ex) { throw new Error("Updating author failed. Details: " + ex.message); } // becomes var updatePromise = updateAuthor(data).then(undefined, function (ex) { throw new Error("Updating author failed. Details: " + ex.message); });
  • 23. Async Case: Waiting var name = promptForNewAuthorName(); updateAuthor({ name: name }); refreshScreen(); // becomes promptForNewAuthorName() .then(function (name) { return updateAuthor({ name: name }); }) .then(refreshScreen);
  • 27. jQuery - q differences • https://github.com/kriskowal/q/wiki/Coming-from-jQuery jQuery Q Notes then then Q's then, and in fact all of its methods, have different exception-handling behavior, as described above. done then then does not support multiple handlers; use multiple calls to then to attach them. fail catch catch does not support multiple handlers; use multiple calls to catch to attach them. deferred.promise(method) deferred.promise(property) You *must* get the promise part of the deferred; the deferred does not have the promise API.
  • 28. Node and q library
  • 30. AngularJS – Limitations of Promise in Angular In Angular's $Q implementation, If you don't fire off $scope.$apply(), after resolving, the resolved values will never propagate to your 'then' functions. Sometimes I want to use promises that aren't tied to my Angular $digest cycle.
  • 31. URLs Credit goes to all the people for sharing their thoughts: • http://wiki.commonjs.org/wiki/Promises/A • http://promisesaplus.com/ • http://promisesaplus.com/differences-from-promises-a • http://api.jquery.com/category/deferred-object/ • http://sitr.us/2012/07/31/promise-pipelines-in-javascript.html • http://stackoverflow.com/questions/12160785/jquery-deferred-promise-design-patterns-and-use-cases • http://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript • http://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done • http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics • https://gist.github.com/domenic/3889970 • http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/ • https://github.com/kriskowal/q • https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md • http://james.padolsey.com/jquery/#v=2.0.3&fn=jQuery.Deferred • http://www.dwmkerr.com/promises-in-angularjs-the-definitive-guide/ • http://spion.github.io/posts/why-i-am-switching-to-promises.html • http://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/
  • 32. Q &A