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

Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communicationAlexe Bogdan
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Ember and containers
Ember and containersEmber and containers
Ember and containersMatthew Beale
 
Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Silex and Twig (PHP Dorset talk)
Silex and Twig (PHP Dorset talk)Dave Hulbert
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Practical Protocols with Associated Types
Practical Protocols with Associated TypesPractical Protocols with Associated Types
Practical Protocols with Associated TypesNatasha Murashev
 
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 KarmaExoLeaders.com
 
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/OTPMaciej Kaszubowski
 
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 ClojureScriptLeonardo Borges
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POPNatasha Murashev
 
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 MottoFuture Insights
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
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]Iakiv Kramarenko
 

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?

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
 
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 2016Codemotion
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service WorkerAnna Su
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Introducing Applitude: Simple Module Management
Introducing Applitude: Simple Module ManagementIntroducing Applitude: Simple Module Management
Introducing Applitude: Simple Module ManagementEric Hamilton
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularErik Guzman
 
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
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 

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 acceptanceIT Weekend
 
Mobile development for JavaScript developer
Mobile development for JavaScript developerMobile development for JavaScript developer
Mobile development for JavaScript developerIT Weekend
 
Building an Innovation & Strategy Process
Building an Innovation & Strategy ProcessBuilding an Innovation & Strategy Process
Building an Innovation & Strategy ProcessIT Weekend
 
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 PlaceIT Weekend
 
Building a Data Driven Organization
Building a Data Driven OrganizationBuilding a Data Driven Organization
Building a Data Driven OrganizationIT Weekend
 
7 Tools for the Product Owner
7 Tools for the Product Owner 7 Tools for the Product Owner
7 Tools for the Product Owner IT Weekend
 
Hacking your Doorbell
Hacking your DoorbellHacking your Doorbell
Hacking your DoorbellIT Weekend
 
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 timeIT Weekend
 
Web services automation from sketch
Web services automation from sketchWeb services automation from sketch
Web services automation from sketchIT Weekend
 
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 cryIT Weekend
 
Как договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общенияКак договариваться с начальником и заказчиком: выбираем нужный протокол общения
Как договариваться с начальником и заказчиком: выбираем нужный протокол общенияIT Weekend
 
Обзор программы SAP HANA Startup Focus
Обзор программы SAP HANA Startup FocusОбзор программы SAP HANA Startup Focus
Обзор программы SAP HANA Startup FocusIT Weekend
 
World of Agile: Kanban
World of Agile: KanbanWorld of Agile: Kanban
World of Agile: KanbanIT Weekend
 
Risk Management
Risk ManagementRisk Management
Risk ManagementIT Weekend
 
«Spring Integration as Integration Patterns Provider»
«Spring Integration as Integration Patterns Provider»«Spring Integration as Integration Patterns Provider»
«Spring Integration as Integration Patterns Provider»IT Weekend
 
Cutting edge of Machine Learning
Cutting edge of Machine LearningCutting edge of Machine Learning
Cutting edge of Machine LearningIT Weekend
 
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 TechnicsIT 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 sharedIT Weekend
 
Maximize Effectiveness of Human Capital
Maximize Effectiveness of Human CapitalMaximize Effectiveness of Human Capital
Maximize Effectiveness of Human CapitalIT 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

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 

Recently uploaded (20)

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 

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