SlideShare a Scribd company logo
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 ).
JavaScript Promises
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 (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Callback Function
Callback FunctionCallback Function
Callback Function
Roland San Nicolas
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
NexThoughts Technologies
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Dinesh U
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
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!
 
React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
React js
React jsReact js
React js
Rajesh Kolla
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 

Viewers also liked (13)

Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
Domenic Denicola
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
Joseph Chiang
 
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
Hans-Gunther Schmidt
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
Łukasz Kużyński
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Tomasz Bak
 
Cloud Platform as a Service: Heroku
Cloud Platform as a Service: HerokuCloud Platform as a Service: Heroku
Cloud Platform as a Service: Heroku
L&T Technology Services Limited
 
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
Solution4Future
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
L&T Technology Services Limited
 
Pragmatics
PragmaticsPragmatics
Pragmatics
JESSIE GRACE RUBRICO
 
Speech acts
Speech actsSpeech acts
Speech acts
Carolina Celis
 
Speech acts
Speech actsSpeech acts
Speech acts
Yirmanny
 
Ad

Similar to JavaScript Promises (20)

Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise PatternPromises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Christian Lilley
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
 
Promises, The Tao of Angular
Promises, The Tao of AngularPromises, The Tao of Angular
Promises, The Tao of Angular
vmlf
 
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
Ankit Agarwal
 
You promise?
You promise?You promise?
You promise?
IT Weekend
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
 
Promises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScriptPromises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScript
Dean Radcliffe
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises
Senthil Kumar
 
Promises in JavaScript with jQuery
Promises in JavaScript with jQueryPromises in JavaScript with jQuery
Promises in JavaScript with jQuery
Ryan Blunden
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise PatternPromises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Christian Lilley
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
 
Promises, The Tao of Angular
Promises, The Tao of AngularPromises, The Tao of Angular
Promises, The Tao of Angular
vmlf
 
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
Ankit Agarwal
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
 
Promises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScriptPromises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScript
Dean Radcliffe
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises
Senthil Kumar
 
Promises in JavaScript with jQuery
Promises in JavaScript with jQueryPromises in JavaScript with jQuery
Promises in JavaScript with jQuery
Ryan Blunden
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
 
Ad

Recently uploaded (17)

5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
Reversed Out Creative
 
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your BusinessCloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
DanaJohnson510230
 
Networking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspectsNetworking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspects
amansinght675
 
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptxTransport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
ssuser80a7e81
 
How to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real TalkHow to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real Talk
Cam Sites Expert
 
all Practical Project LAST summary note.docx
all Practical Project LAST summary note.docxall Practical Project LAST summary note.docx
all Practical Project LAST summary note.docx
seidjemal94
 
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
Taqyea
 
Presentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIKPresentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIK
SELMA SALTIK
 
ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676
areebaimtiazpmas
 
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AIAI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
skdav34
 
Networking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptxNetworking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptx
elestirmen
 
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdfEssential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
CartCoders
 
basic to advance network security concepts
basic to advance network security conceptsbasic to advance network security concepts
basic to advance network security concepts
amansinght675
 
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdfFrontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Internet Bundle Now
 
HPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptxHPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptx
naziaahmadnm
 
OSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptxOSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptx
faizanaseem873
 
10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx
EphraimOOghodero
 
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
Reversed Out Creative
 
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your BusinessCloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
DanaJohnson510230
 
Networking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspectsNetworking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspects
amansinght675
 
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptxTransport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
ssuser80a7e81
 
How to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real TalkHow to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real Talk
Cam Sites Expert
 
all Practical Project LAST summary note.docx
all Practical Project LAST summary note.docxall Practical Project LAST summary note.docx
all Practical Project LAST summary note.docx
seidjemal94
 
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
Taqyea
 
Presentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIKPresentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIK
SELMA SALTIK
 
ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676
areebaimtiazpmas
 
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AIAI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
skdav34
 
Networking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptxNetworking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptx
elestirmen
 
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdfEssential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
CartCoders
 
basic to advance network security concepts
basic to advance network security conceptsbasic to advance network security concepts
basic to advance network security concepts
amansinght675
 
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdfFrontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Internet Bundle Now
 
HPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptxHPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptx
naziaahmadnm
 
OSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptxOSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptx
faizanaseem873
 
10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx
EphraimOOghodero
 

JavaScript Promises

  • 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 ).
  • 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