SlideShare ist ein Scribd-Unternehmen logo
1 von 32
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

Weitere ähnliche Inhalte

Ähnlich wie Promises, The Tao of Angular

Walkthrough madness: an introduction to all the amazing things you can do wit...
Walkthrough madness: an introduction to all the amazing things you can do wit...Walkthrough madness: an introduction to all the amazing things you can do wit...
Walkthrough madness: an introduction to all the amazing things you can do wit...
Kristof Van Tomme
 
Keyboard_Kung_Fu
Keyboard_Kung_FuKeyboard_Kung_Fu
Keyboard_Kung_Fu
Craig Angus
 

Ähnlich wie Promises, The Tao of Angular (20)

Dear compiler please don't be my nanny v2
Dear compiler  please don't be my nanny v2Dear compiler  please don't be my nanny v2
Dear compiler please don't be my nanny v2
 
Passing the Joel Test in the PHP World (phpbnl10)
Passing the Joel Test in the PHP World (phpbnl10)Passing the Joel Test in the PHP World (phpbnl10)
Passing the Joel Test in the PHP World (phpbnl10)
 
Era of declarative ui
Era of declarative uiEra of declarative ui
Era of declarative ui
 
Go/Ruby/Java: What's next?
Go/Ruby/Java: What's next?Go/Ruby/Java: What's next?
Go/Ruby/Java: What's next?
 
TDC 2020 - Implementing a Mini-Language
TDC 2020 - Implementing a Mini-LanguageTDC 2020 - Implementing a Mini-Language
TDC 2020 - Implementing a Mini-Language
 
Reversed Test Pyramid - Testing and dealing with Legacy Code
Reversed Test Pyramid - Testing and dealing with Legacy CodeReversed Test Pyramid - Testing and dealing with Legacy Code
Reversed Test Pyramid - Testing and dealing with Legacy Code
 
Sqa days2013
Sqa days2013Sqa days2013
Sqa days2013
 
Impossible Programs
Impossible ProgramsImpossible Programs
Impossible Programs
 
Walkthrough madness: an introduction to all the amazing things you can do wit...
Walkthrough madness: an introduction to all the amazing things you can do wit...Walkthrough madness: an introduction to all the amazing things you can do wit...
Walkthrough madness: an introduction to all the amazing things you can do wit...
 
Kickstart programing part 2
Kickstart programing   part 2Kickstart programing   part 2
Kickstart programing part 2
 
Building High-Quality Apps for Google Assistant
Building High-Quality Apps for Google AssistantBuilding High-Quality Apps for Google Assistant
Building High-Quality Apps for Google Assistant
 
The Ring programming language version 1.6 book - Part 181 of 189
The Ring programming language version 1.6 book - Part 181 of 189The Ring programming language version 1.6 book - Part 181 of 189
The Ring programming language version 1.6 book - Part 181 of 189
 
Designing a Conversational Intelligent Bot which can cook
Designing a Conversational Intelligent Bot which can cookDesigning a Conversational Intelligent Bot which can cook
Designing a Conversational Intelligent Bot which can cook
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
Why the h# should I use Appium with React Native
Why the h# should I use Appium with React NativeWhy the h# should I use Appium with React Native
Why the h# should I use Appium with React Native
 
Go lang
Go langGo lang
Go lang
 
Asynchronous programming with Functional Java and comparison with Scala
Asynchronous programming with Functional Java and comparison with ScalaAsynchronous programming with Functional Java and comparison with Scala
Asynchronous programming with Functional Java and comparison with Scala
 
Xp days ukraine 2012
Xp days ukraine 2012Xp days ukraine 2012
Xp days ukraine 2012
 
Keyboard_Kung_Fu
Keyboard_Kung_FuKeyboard_Kung_Fu
Keyboard_Kung_Fu
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/await
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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 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
  • 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 vmlf01@gmail.com AngularJS Portugal meetup.com/AngularJS-Portugal/ twitter.com/angularjspt Google+ community Thanks