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

What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...Edureka!
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? EdurekaEdureka!
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 

What's hot (20)

What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Express js
Express jsExpress js
Express js
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? Edureka
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Fetch API Talk
Fetch API TalkFetch API Talk
Fetch API Talk
 
Jquery
JqueryJquery
Jquery
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 

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

Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
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
 
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
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
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
 
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
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 

Recently uploaded (20)

Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
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
 
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
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
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
 
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...
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 

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