SlideShare a Scribd company logo
promises
the tao of angular
AngularJS Portugal
meetup.com/AngularJS-Portugal/
twitter.com/angularjspt
Google+ community
Vitor Fernandes
vmlf01@gmail.com
● 15+ years developer
● CTO with Gotv Media Software since 2002
● Creator of AngularJS Portugal group
Visual Basic 5, Microsoft WebTv ASP/Jscript, .Net Framework 1 through
4.5 desktop apps, Titanium Mobile Javascript Mobile apps,
AngularJS last 2 months
/$ whoami
promises
the tao of angular
_________________________________
Source code:
github.com/vmlf01/promiseSamples
Preview:
promisesamples.divshot.io
What are promises?
A promise is a container that holds or will hold a value
WHAT?!?
It's a trust thing!
With promises, you are always guaranteed
to get one and only one value back
(even if it's a failure)
Trust me :)
what are promises
What do they do?
Promises are a way of thinking synchronously
and doing asynchronously.
What is it good for?!
Unlike war, absolutely everything.
Say it again!
what are promises 1
A promise can be:
 Pending
 Fulfilled
 Rejected
Once a Promise is fulfilled or rejected, it’ll remain in
that state forever.
promise states 2
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.
the promised land in angular, domenic denicola
promise guarantees 3
Dinner out:
1.How many people?
2.Which restaurant?
3.Book restaurant
4.Show up on time
5.Eat
programming 101: algorithms
Dinner out:
Well that's all fine and dandy,
but what about the other stuff?
In reality, you cannot block waiting for each step
to complete. You need to go about your life!
(Web) programming is async.
programming 101: algorithms
Dinner out:
1.How many people?
2.Which restaurant?
3.Book restaurant
4.Show up on time
5.Eat
parallel execution
Done at
same time
Dinner out:
1.How many people?
2.Which restaurant?
3.Book restaurant
4.Show up on time
5.Eat
handle exceptions
What if not
available?
Dinner out:
1.How many people?
2.Which restaurant?
3.Book restaurant
4.Show up on time
5.Eat
don't block, give feedback
Table not ready,
wait a bit
Dinner out:
1.How many people?
2.Which restaurant?
3.Book restaurant
4.Show up on time
5.Eat
finally
● Implemented in AngularJS $q service
● Inspired by Kris Kowal's Q library
● Contains only the most important features
● Integrated with AngularJS's digest/event loop
promises in AngularJS
function aSimplePromise() {
var deferredTask = $q.defer();
deferredTask.resolve(
'I always keep my promises!'
);
return deferredTask.promise;
}
$q
The deferred API
var deferred = $q.defer()
deferred.resolve(value)
deferred.reject(reason)
deferred.notify(status)
var promise = deferred.promise
$q
The promise API
promise.then(onFulfilled, onRejected, onNotify)
promise.catch(onRejected)
promise.finally(callback)
$q
The Helpers
var promise = $q.when(value)
var promise = $q.all([arrayOfPromises])
$q
AngularJS digest cycle
the promised land in angular, domenic denicola
function MyController($scope, $http) {
$scope.text = "loading";
$scope.doThing = function () {
$http.get("somefile.json").then(function (response) {
$scope.text = response.data;
});
};
}
// Works! Angular’s promises are integrated into the digest cycle
the promised land in angular, domenic denicola
$q resolution inside digest cycle 4
Promises are all around in AngularJS!
$http
$resource
$route
$timeout
...
The Tao of Angular
● then() returns a promise
● Callback return values fulfill their promises
● Callback errors reject their promises
● Value/reason passthru if callback missing
● Callbacks can return promises
the 5 commandments
promises. the basics, from promises/A+, luke smith
5..9
Can we live without them?
...
Why would you?
● Wasted promises → Garbage collection
● Silent fails
promises problems
● Cleaner method signatures
● Uniform return/error semantics
● Easy composition
● Easy sequential/parallel join
● Always async
● Exception-style error bubbling
why promises are awesome
callbacks, promises, and coroutines (oh my!), domenic denicola
Wait, wait, wait...
But how does it work?
how do promises work?
Well, eh...
Js promises are just
callbacks
in hidding!
Did you think it was magic???
how do promises work
function Promise(fn)
var state = 'pending';
var value;
var deferred = null;
function resolve(newValue) {
value = newValue;
state = 'resolved';
if(deferred) {
handle(deferred);
}
}
function handle(handler) {
if(state === 'pending') {
deferred = handler;
return;
}
if(!handler.onResolved) {
handler.resolve(value);
return;
}
var ret = handler.onResolved(value);
handler.resolve(ret);
}
function Promise(fn)
this.then = function(onResolved) {
return new Promise(function(resolve) {
handle({
onResolved: onResolved,
resolve: resolve
});
});
};
fn(resolve);
promise call flow
promise
.resolve()
.then()
.handle()
Add a new promise
to the chain
Resolve current promiseand next in chain
function handle(handler)
If promise state is pending, store handler to call it
back later when promise resolves
If there is no onResolved callback for this promise,
then take its value and passthru to next promise in
chain
Call this promise onResolved handler
Then, resolve next promise in chain with the return
value
function handle(handler) {
if(state === 'pending') {
deferred = handler;
return;
}
if(!handler.onResolved) {
handler.resolve(value);
return;
}
var ret = handler.onResolved(value);
handler.resolve(ret);
}
Promises/A+ Specification
http://promises-aplus.github.io/promises-spec/
Callbacks, Promises, and Coroutines (oh my!), Domenic Denicola
http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asyn
The Promised Land in Angular, Domenic Denicola
http://www.slideshare.net/domenicdenicola/the-promised-land-in-angular
Promises, Luke Smith
http://www.slideshare.net/drprolix/promises-16473115
JavaScript Promises ... In Wicked Detail, Matt Greer
http://www.mattgreer.org/articles/promises-in-wicked-detail/
references
promises
the way of the angular
Vitor Fernandes
vmlf01@gmail.com
AngularJS Portugal
meetup.com/AngularJS-Portugal/
twitter.com/angularjspt
Google+ community
Thanks

More Related Content

Similar to Promises, The Tao of Angular (20)

PPTX
Dear compiler please don't be my nanny v2
Dino Dini
 
PDF
Passing the Joel Test in the PHP World (phpbnl10)
Lorna Mitchell
 
PPTX
"10 Pitfalls of a Platform Team", Yura Rochniak
Fwdays
 
PDF
Era of declarative ui
Sadman Samee
 
PPTX
Go/Ruby/Java: What's next?
Hernan Wilkinson
 
PDF
TDC 2020 - Implementing a Mini-Language
Luciano Sabença
 
ODP
Sqa days2013
Wiktor Żołnowski
 
ODP
Reversed Test Pyramid - Testing and dealing with Legacy Code
SQALab
 
PDF
Impossible Programs
C4Media
 
PDF
Walkthrough madness: an introduction to all the amazing things you can do wit...
Kristof Van Tomme
 
PPTX
Kickstart programing part 2
Hosein Nourani
 
PDF
Building High-Quality Apps for Google Assistant
Peter Friese
 
PDF
The Ring programming language version 1.6 book - Part 181 of 189
Mahmoud Samir Fayed
 
PDF
Designing a Conversational Intelligent Bot which can cook
Kaushik Das
 
PDF
PHP, Under The Hood - DPC
Anthony Ferrara
 
PDF
Why the h# should I use Appium with React Native
Wim Selles
 
PDF
Go lang
Suelen Carvalho
 
ODP
Asynchronous programming with Functional Java and comparison with Scala
Knoldus Inc.
 
ODP
Xp days ukraine 2012
Wiktor Żołnowski
 
PPTX
Keyboard_Kung_Fu
Craig Angus
 
Dear compiler please don't be my nanny v2
Dino Dini
 
Passing the Joel Test in the PHP World (phpbnl10)
Lorna Mitchell
 
"10 Pitfalls of a Platform Team", Yura Rochniak
Fwdays
 
Era of declarative ui
Sadman Samee
 
Go/Ruby/Java: What's next?
Hernan Wilkinson
 
TDC 2020 - Implementing a Mini-Language
Luciano Sabença
 
Sqa days2013
Wiktor Żołnowski
 
Reversed Test Pyramid - Testing and dealing with Legacy Code
SQALab
 
Impossible Programs
C4Media
 
Walkthrough madness: an introduction to all the amazing things you can do wit...
Kristof Van Tomme
 
Kickstart programing part 2
Hosein Nourani
 
Building High-Quality Apps for Google Assistant
Peter Friese
 
The Ring programming language version 1.6 book - Part 181 of 189
Mahmoud Samir Fayed
 
Designing a Conversational Intelligent Bot which can cook
Kaushik Das
 
PHP, Under The Hood - DPC
Anthony Ferrara
 
Why the h# should I use Appium with React Native
Wim Selles
 
Asynchronous programming with Functional Java and comparison with Scala
Knoldus Inc.
 
Xp days ukraine 2012
Wiktor Żołnowski
 
Keyboard_Kung_Fu
Craig Angus
 

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
PDF
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
PDF
Deploy Faster, Run Smarter: Learn Containers with QNAP
QNAP Marketing
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
PDF
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
Deploy Faster, Run Smarter: Learn Containers with QNAP
QNAP Marketing
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Practical Applications of AI in Local Government
OnBoard
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Kubernetes - Architecture & Components.pdf
geethak285
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Ad

Promises, The Tao of Angular

  • 1. promises the tao of angular AngularJS Portugal meetup.com/AngularJS-Portugal/ twitter.com/angularjspt Google+ community
  • 2. Vitor Fernandes [email protected] ● 15+ years developer ● CTO with Gotv Media Software since 2002 ● Creator of AngularJS Portugal group Visual Basic 5, Microsoft WebTv ASP/Jscript, .Net Framework 1 through 4.5 desktop apps, Titanium Mobile Javascript Mobile apps, AngularJS last 2 months /$ whoami
  • 3. promises the tao of angular _________________________________ Source code: github.com/vmlf01/promiseSamples Preview: promisesamples.divshot.io
  • 4. What are promises? A promise is a container that holds or will hold a value WHAT?!? It's a trust thing! With promises, you are always guaranteed to get one and only one value back (even if it's a failure) Trust me :) what are promises
  • 5. What do they do? Promises are a way of thinking synchronously and doing asynchronously. What is it good for?! Unlike war, absolutely everything. Say it again! what are promises 1
  • 6. A promise can be:  Pending  Fulfilled  Rejected Once a Promise is fulfilled or rejected, it’ll remain in that state forever. promise states 2
  • 7. 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. the promised land in angular, domenic denicola promise guarantees 3
  • 8. Dinner out: 1.How many people? 2.Which restaurant? 3.Book restaurant 4.Show up on time 5.Eat programming 101: algorithms
  • 9. Dinner out: Well that's all fine and dandy, but what about the other stuff? In reality, you cannot block waiting for each step to complete. You need to go about your life! (Web) programming is async. programming 101: algorithms
  • 10. Dinner out: 1.How many people? 2.Which restaurant? 3.Book restaurant 4.Show up on time 5.Eat parallel execution Done at same time
  • 11. Dinner out: 1.How many people? 2.Which restaurant? 3.Book restaurant 4.Show up on time 5.Eat handle exceptions What if not available?
  • 12. Dinner out: 1.How many people? 2.Which restaurant? 3.Book restaurant 4.Show up on time 5.Eat don't block, give feedback Table not ready, wait a bit
  • 13. Dinner out: 1.How many people? 2.Which restaurant? 3.Book restaurant 4.Show up on time 5.Eat finally
  • 14. ● Implemented in AngularJS $q service ● Inspired by Kris Kowal's Q library ● Contains only the most important features ● Integrated with AngularJS's digest/event loop promises in AngularJS
  • 15. function aSimplePromise() { var deferredTask = $q.defer(); deferredTask.resolve( 'I always keep my promises!' ); return deferredTask.promise; } $q
  • 16. The deferred API var deferred = $q.defer() deferred.resolve(value) deferred.reject(reason) deferred.notify(status) var promise = deferred.promise $q
  • 17. The promise API promise.then(onFulfilled, onRejected, onNotify) promise.catch(onRejected) promise.finally(callback) $q
  • 18. The Helpers var promise = $q.when(value) var promise = $q.all([arrayOfPromises]) $q
  • 19. AngularJS digest cycle the promised land in angular, domenic denicola
  • 20. function MyController($scope, $http) { $scope.text = "loading"; $scope.doThing = function () { $http.get("somefile.json").then(function (response) { $scope.text = response.data; }); }; } // Works! Angular’s promises are integrated into the digest cycle the promised land in angular, domenic denicola $q resolution inside digest cycle 4
  • 21. Promises are all around in AngularJS! $http $resource $route $timeout ... The Tao of Angular
  • 22. ● then() returns a promise ● Callback return values fulfill their promises ● Callback errors reject their promises ● Value/reason passthru if callback missing ● Callbacks can return promises the 5 commandments promises. the basics, from promises/A+, luke smith 5..9
  • 23. Can we live without them? ... Why would you? ● Wasted promises → Garbage collection ● Silent fails promises problems
  • 24. ● Cleaner method signatures ● Uniform return/error semantics ● Easy composition ● Easy sequential/parallel join ● Always async ● Exception-style error bubbling why promises are awesome callbacks, promises, and coroutines (oh my!), domenic denicola
  • 25. Wait, wait, wait... But how does it work? how do promises work?
  • 26. Well, eh... Js promises are just callbacks in hidding! Did you think it was magic??? how do promises work
  • 27. function Promise(fn) var state = 'pending'; var value; var deferred = null; function resolve(newValue) { value = newValue; state = 'resolved'; if(deferred) { handle(deferred); } } function handle(handler) { if(state === 'pending') { deferred = handler; return; } if(!handler.onResolved) { handler.resolve(value); return; } var ret = handler.onResolved(value); handler.resolve(ret); }
  • 28. function Promise(fn) this.then = function(onResolved) { return new Promise(function(resolve) { handle({ onResolved: onResolved, resolve: resolve }); }); }; fn(resolve);
  • 29. promise call flow promise .resolve() .then() .handle() Add a new promise to the chain Resolve current promiseand next in chain
  • 30. function handle(handler) If promise state is pending, store handler to call it back later when promise resolves If there is no onResolved callback for this promise, then take its value and passthru to next promise in chain Call this promise onResolved handler Then, resolve next promise in chain with the return value function handle(handler) { if(state === 'pending') { deferred = handler; return; } if(!handler.onResolved) { handler.resolve(value); return; } var ret = handler.onResolved(value); handler.resolve(ret); }
  • 31. Promises/A+ Specification http://promises-aplus.github.io/promises-spec/ Callbacks, Promises, and Coroutines (oh my!), Domenic Denicola http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asyn The Promised Land in Angular, Domenic Denicola http://www.slideshare.net/domenicdenicola/the-promised-land-in-angular Promises, Luke Smith http://www.slideshare.net/drprolix/promises-16473115 JavaScript Promises ... In Wicked Detail, Matt Greer http://www.mattgreer.org/articles/promises-in-wicked-detail/ references
  • 32. promises the way of the angular Vitor Fernandes [email protected] AngularJS Portugal meetup.com/AngularJS-Portugal/ twitter.com/angularjspt Google+ community Thanks