SlideShare a Scribd company logo
1 of 39
You promise?
By Volodymyr Pavlyuk
Volodymyr Pavlyuk
• Almost 10 years in software development industry
• Web UI expert at SoftServe
Facebook: www.facebook.com/volopav
You can even follow me on Instagram – @volopav
Warning!
This presentation contains programming
code.
No cats beyond this point!
The Problem
Asynchronous JavaScript
APIs
// Synchronous
var contents = readFile('file.txt');
// …becomes
readFile('file.txt', function(err, contents) {
// Process result here
// Note, that there is no return
});
Error handling is ugly
readFile('file.txt', function(err, contents) {
if (error) {
handleError();
} else {
// do something with contents
}
});
You can’t throw!
readFile('file.txt', function(err, contents) {
if (error) throw error; // <- no one will catch it
});
You can’t throw!
function causeException() {
something.prop; // <- this causes exception
}
try {
setTimeout(function() {
causeException();
}, 0);
} catch (e) {
console.log(e); // <- will never get here
}
Chaining
getUser("UserName", function (user) {
getBestFriend(user, function (friend) {
ui.showBestFriend(friend);
});
});
Even worse with error
handling
getUser("UserName", function (err, user) {
if (err) {
ui.error(err);
} else {
getBestFriend(user, function (err, friend) {
if (err) {
ui.error(err);
} else {
ui.showBestFriend(friend);
}
});
}
});
Callbacks are hell
• No return
• No throw
• No consistency in callback API’s
• No guarantees: callback can be called
once, multiple times or not called at all
Callbacks are a hack
• They are literally the simplest thing that could
work.
• But as a replacement for synchronous control
flow, they suck.
• We lose the flow of our code writing callbacks
that tie together other callbacks.
Any solution?
Promises/A+
Promises are the right
abstraction
Instead of calling a passed callback, return a
promise:
readFile('file.txt', function(err, contents) {
// Process result here
});
// becomes
var promiseForContents = readFile("file.txt");
A promise is an
ASYNCHRONOU
S value
Promise guarantees
var promiseForResult = readFile(“file.txt”);
promiseForResult.then(
function onFulfilled(result) {
// Precess result
},
function onRejected(reason) {
// handle error
}
);
https://github.com/promises-
aplus/promises-spec
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.
Promises can be chained
var transformedPromise = originalPromise.then(onFulfilled,
onRejected);
• If the called handler returns a value, transformedPromise will be resolved with
that value:
• If the returned value is a promise, we adopt its state.
• Otherwise, transformedPromise is fulfilled with that value.
• If the called handler throws an exception, transformedPromise will be rejected
with that exception.
Keep The Sync ⇔ Async Parallel In
Mind
Simple Functional Transform
var user = getUser();
var userName = user.name;
// becomes
var userNamePromise = getUser().then(function (user) {
return user.name;
});
Reacting with an Exception
var user = getUser();
if (user === null)
throw new Error("null user!");
//becomes
var userPromise = getUser().then(function (user) {
if (user === null)
throw new Error("null user!");
return user;
});
Handling an Exception
try {
deliverPizzaTo(tweet, 'volopav');
} catch (error) {
handleError(error);
}
// becomes
deliverPizzaTo(tweet, 'volopav')
.then(undefined, handleError)
Rethrowing an Exception
try {
var user = getUser('volopav');
} catch (error) {
throw new Error('ERROR: ' + error.message);
}
// becomes
getUser('volopav').then(undefined, function(error) {
throw new Error('ERROR: ' + error.message);
});
Chaining
getUser("volopav", function (user) {
getBestFriend(user, function (friend) {
ui.showBestFriend(friend);
});
});
// becomes
getUser("volopav")
.then(getBestFriend)
.then(ui.showBestFriend, ui.showError)
Promises as First-Class
Objects
Because promises are first-class objects, you can build simple
operations on them instead of tying callbacks together:
// Fulfills with an array of results, or rejects if any reject
all([getUserData(), getCompanyData()]);
// Fulfills as soon as either completes, or rejects if both reject
any([storeDataOnServer1(), storeDataOnServer2()]);
// If writeFile accepts promises as arguments, and readFile returns one:
writeFile("dest.txt", readFile("source.txt"));
Promise Patterns: all + spread
all([getUser(), getCompany()]).then(function (results) {
console.log("user = ", results[0]);
console.log("company = ", results[1]);
}).done();
all([getUser(), getCompany()]).spread(function (user, company) {
console.log("user = ", user);
console.log("company = ", company);
}).done();
Promise Patterns:
try/catch/finally
ui.startSpinner();
getUser("volopav")
.then(getBestFriend)
.then(ui.showBestFriend)
.catch(ui.error)
.finally(ui.stopSpinner)
.done();
Promise Patterns: map + all
var userIds = ["123", "456", "789"];
all(userIds.map(getUserById))
.then(function (users) {
console.log("all the users: ", users);
})
.done();
This is looking nice, but I don’t
have APIs which return
promises?
Choose a Library
Best implementations:
• Q, by Kris Kowal and Domenic:
https://github.com/kriskowal/q
• When.js, by Brian Cavalier: https://github.com/cujojs/when
• RSVP.js, by Yehuda Katz: https://github.com/tildeio/rsvp.js
$.Deferred
• jQuery’s $.Deferred is a very buggy attempted
implementation, that entirely misses the sync ⇔ async
parallel
• If you ever see a jQuery promise, kill it with fire:
var realPromise = Q(jQueryPromise);
var realPromise = when(jQueryPromise);
function getUser(name) {
var defer = Q.defer();
ajax(url, {name: name}, function(err, response) {
if (err) {
defer.reject(err);
} else {
defer.resolve(response);
}
});
return defer.promise;
}
Denodify
var readFile = Q.denodeify(fs.readFile);
var readDir = Q.denodeify(fs.readdir);
readDir("/tmp")
.get("0")
.then(readFile)
.then(function (data) {
console.log("The first temporary file contains: ", data);
})
.catch(function (error) {
console.log("One of the steps failed: ", error);
})
.done();
ES6 native support of
promises
http://www.html5rocks.com/en/tutorials/es6/promi
ses/
So native APIs will return promises!
Keep The Sync ⇔ Async Parallel In
Mind
• Use promises for single operations that can result in fulfillment
( returning a value) or rejection ( throwing an exception).
• If you’re ever stuck, ask “how would I structure this code if it
were synchronous?”
• The only exception is multiple parallel operations, which has no sync
counterpart.
Promises Are Not
• A replacement for events
• A replacement for streams
• A way of doing functional reactive programming
They work together:
• An event can trigger from one part of your UI, causing the event
handler to trigger a promise-returning function
• A HTTP request function can return a promise for a stream
Questions?

More Related Content

What's hot

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 

What's hot (20)

Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communication
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Practical Protocols with Associated Types
Practical Protocols with Associated TypesPractical Protocols with Associated Types
Practical Protocols with Associated Types
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Let it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTPLet it crash - fault tolerance in Elixir/OTP
Let it crash - fault tolerance in Elixir/OTP
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Intro to Silex
Intro to SilexIntro to Silex
Intro to Silex
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
 
Angular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd MottoAngular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd Motto
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
Excellent
ExcellentExcellent
Excellent
 

Similar to You promise?

Introducing Applitude: Simple Module Management
Introducing Applitude: Simple Module ManagementIntroducing Applitude: Simple Module Management
Introducing Applitude: Simple Module Management
Eric Hamilton
 

Similar to You promise? (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript 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...
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service Worker
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Introducing Applitude: Simple Module Management
Introducing Applitude: Simple Module ManagementIntroducing Applitude: Simple Module Management
Introducing Applitude: Simple Module Management
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
20150319 testotipsio
20150319 testotipsio20150319 testotipsio
20150319 testotipsio
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
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
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 

More from IT Weekend

Quality attributes testing. From Architecture to test acceptance
Quality attributes testing. From Architecture to test acceptanceQuality attributes testing. From Architecture to test acceptance
Quality attributes testing. From Architecture to test acceptance
IT Weekend
 
Как договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общенияКак договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общения
IT Weekend
 
Parallel programming in modern world .net technics shared
Parallel programming in modern world .net technics   sharedParallel programming in modern world .net technics   shared
Parallel programming in modern world .net technics shared
IT Weekend
 

More from IT Weekend (20)

Quality attributes testing. From Architecture to test acceptance
Quality attributes testing. From Architecture to test acceptanceQuality attributes testing. From Architecture to test acceptance
Quality attributes testing. From Architecture to test acceptance
 
Mobile development for JavaScript developer
Mobile development for JavaScript developerMobile development for JavaScript developer
Mobile development for JavaScript developer
 
Building an Innovation & Strategy Process
Building an Innovation & Strategy ProcessBuilding an Innovation & Strategy Process
Building an Innovation & Strategy Process
 
IT Professionals – The Right Time/The Right Place
IT Professionals – The Right Time/The Right PlaceIT Professionals – The Right Time/The Right Place
IT Professionals – The Right Time/The Right Place
 
Building a Data Driven Organization
Building a Data Driven OrganizationBuilding a Data Driven Organization
Building a Data Driven Organization
 
7 Tools for the Product Owner
7 Tools for the Product Owner 7 Tools for the Product Owner
7 Tools for the Product Owner
 
Hacking your Doorbell
Hacking your DoorbellHacking your Doorbell
Hacking your Doorbell
 
An era of possibilities, a window in time
An era of possibilities, a window in timeAn era of possibilities, a window in time
An era of possibilities, a window in time
 
Web services automation from sketch
Web services automation from sketchWeb services automation from sketch
Web services automation from sketch
 
Why Ruby?
Why Ruby? Why Ruby?
Why Ruby?
 
REST that won't make you cry
REST that won't make you cryREST that won't make you cry
REST that won't make you cry
 
Как договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общенияКак договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общения
 
Обзор программы SAP HANA Startup Focus
Обзор программы SAP HANA Startup FocusОбзор программы SAP HANA Startup Focus
Обзор программы SAP HANA Startup Focus
 
World of Agile: Kanban
World of Agile: KanbanWorld of Agile: Kanban
World of Agile: Kanban
 
Risk Management
Risk ManagementRisk Management
Risk Management
 
«Spring Integration as Integration Patterns Provider»
«Spring Integration as Integration Patterns Provider»«Spring Integration as Integration Patterns Provider»
«Spring Integration as Integration Patterns Provider»
 
Cutting edge of Machine Learning
Cutting edge of Machine LearningCutting edge of Machine Learning
Cutting edge of Machine Learning
 
Parallel Programming In Modern World .NET Technics
Parallel Programming In Modern World .NET TechnicsParallel Programming In Modern World .NET Technics
Parallel Programming In Modern World .NET Technics
 
Parallel programming in modern world .net technics shared
Parallel programming in modern world .net technics   sharedParallel programming in modern world .net technics   shared
Parallel programming in modern world .net technics shared
 
Maximize Effectiveness of Human Capital
Maximize Effectiveness of Human CapitalMaximize Effectiveness of Human Capital
Maximize Effectiveness of Human Capital
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

You promise?

  • 2. Volodymyr Pavlyuk • Almost 10 years in software development industry • Web UI expert at SoftServe Facebook: www.facebook.com/volopav You can even follow me on Instagram – @volopav
  • 4. No cats beyond this point!
  • 6.
  • 7. Asynchronous JavaScript APIs // Synchronous var contents = readFile('file.txt'); // …becomes readFile('file.txt', function(err, contents) { // Process result here // Note, that there is no return });
  • 8. Error handling is ugly readFile('file.txt', function(err, contents) { if (error) { handleError(); } else { // do something with contents } });
  • 9. You can’t throw! readFile('file.txt', function(err, contents) { if (error) throw error; // <- no one will catch it });
  • 10. You can’t throw! function causeException() { something.prop; // <- this causes exception } try { setTimeout(function() { causeException(); }, 0); } catch (e) { console.log(e); // <- will never get here }
  • 11. Chaining getUser("UserName", function (user) { getBestFriend(user, function (friend) { ui.showBestFriend(friend); }); });
  • 12. Even worse with error handling getUser("UserName", function (err, user) { if (err) { ui.error(err); } else { getBestFriend(user, function (err, friend) { if (err) { ui.error(err); } else { ui.showBestFriend(friend); } }); } });
  • 13. Callbacks are hell • No return • No throw • No consistency in callback API’s • No guarantees: callback can be called once, multiple times or not called at all
  • 14. Callbacks are a hack • They are literally the simplest thing that could work. • But as a replacement for synchronous control flow, they suck. • We lose the flow of our code writing callbacks that tie together other callbacks.
  • 16. Promises are the right abstraction Instead of calling a passed callback, return a promise: readFile('file.txt', function(err, contents) { // Process result here }); // becomes var promiseForContents = readFile("file.txt");
  • 17. A promise is an ASYNCHRONOU S value
  • 18. Promise guarantees var promiseForResult = readFile(“file.txt”); promiseForResult.then( function onFulfilled(result) { // Precess result }, function onRejected(reason) { // handle error } );
  • 19. https://github.com/promises- aplus/promises-spec 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.
  • 20. Promises can be chained var transformedPromise = originalPromise.then(onFulfilled, onRejected); • If the called handler returns a value, transformedPromise will be resolved with that value: • If the returned value is a promise, we adopt its state. • Otherwise, transformedPromise is fulfilled with that value. • If the called handler throws an exception, transformedPromise will be rejected with that exception.
  • 21. Keep The Sync ⇔ Async Parallel In Mind
  • 22. Simple Functional Transform var user = getUser(); var userName = user.name; // becomes var userNamePromise = getUser().then(function (user) { return user.name; });
  • 23. Reacting with an Exception var user = getUser(); if (user === null) throw new Error("null user!"); //becomes var userPromise = getUser().then(function (user) { if (user === null) throw new Error("null user!"); return user; });
  • 24. Handling an Exception try { deliverPizzaTo(tweet, 'volopav'); } catch (error) { handleError(error); } // becomes deliverPizzaTo(tweet, 'volopav') .then(undefined, handleError)
  • 25. Rethrowing an Exception try { var user = getUser('volopav'); } catch (error) { throw new Error('ERROR: ' + error.message); } // becomes getUser('volopav').then(undefined, function(error) { throw new Error('ERROR: ' + error.message); });
  • 26. Chaining getUser("volopav", function (user) { getBestFriend(user, function (friend) { ui.showBestFriend(friend); }); }); // becomes getUser("volopav") .then(getBestFriend) .then(ui.showBestFriend, ui.showError)
  • 27. Promises as First-Class Objects Because promises are first-class objects, you can build simple operations on them instead of tying callbacks together: // Fulfills with an array of results, or rejects if any reject all([getUserData(), getCompanyData()]); // Fulfills as soon as either completes, or rejects if both reject any([storeDataOnServer1(), storeDataOnServer2()]); // If writeFile accepts promises as arguments, and readFile returns one: writeFile("dest.txt", readFile("source.txt"));
  • 28. Promise Patterns: all + spread all([getUser(), getCompany()]).then(function (results) { console.log("user = ", results[0]); console.log("company = ", results[1]); }).done(); all([getUser(), getCompany()]).spread(function (user, company) { console.log("user = ", user); console.log("company = ", company); }).done();
  • 30. Promise Patterns: map + all var userIds = ["123", "456", "789"]; all(userIds.map(getUserById)) .then(function (users) { console.log("all the users: ", users); }) .done();
  • 31. This is looking nice, but I don’t have APIs which return promises?
  • 32. Choose a Library Best implementations: • Q, by Kris Kowal and Domenic: https://github.com/kriskowal/q • When.js, by Brian Cavalier: https://github.com/cujojs/when • RSVP.js, by Yehuda Katz: https://github.com/tildeio/rsvp.js
  • 33. $.Deferred • jQuery’s $.Deferred is a very buggy attempted implementation, that entirely misses the sync ⇔ async parallel • If you ever see a jQuery promise, kill it with fire: var realPromise = Q(jQueryPromise); var realPromise = when(jQueryPromise);
  • 34. function getUser(name) { var defer = Q.defer(); ajax(url, {name: name}, function(err, response) { if (err) { defer.reject(err); } else { defer.resolve(response); } }); return defer.promise; }
  • 35. Denodify var readFile = Q.denodeify(fs.readFile); var readDir = Q.denodeify(fs.readdir); readDir("/tmp") .get("0") .then(readFile) .then(function (data) { console.log("The first temporary file contains: ", data); }) .catch(function (error) { console.log("One of the steps failed: ", error); }) .done();
  • 36. ES6 native support of promises http://www.html5rocks.com/en/tutorials/es6/promi ses/ So native APIs will return promises!
  • 37. Keep The Sync ⇔ Async Parallel In Mind • Use promises for single operations that can result in fulfillment ( returning a value) or rejection ( throwing an exception). • If you’re ever stuck, ask “how would I structure this code if it were synchronous?” • The only exception is multiple parallel operations, which has no sync counterpart.
  • 38. Promises Are Not • A replacement for events • A replacement for streams • A way of doing functional reactive programming They work together: • An event can trigger from one part of your UI, causing the event handler to trigger a promise-returning function • A HTTP request function can return a promise for a stream