SlideShare a Scribd company logo
1 of 15
Download to read offline
$q: how to keep promises with AngularJS
Dominique Dumont
Apr 2018
Dominique Dumont $q promises
What is a promise ?
A way to write a function whose execution is deferred
A way to trigger its execution on an external event
Caveat
This presentation was prepared in 2015 for Angular 1.5. Even if $q
is obsolete now, the techniques shown in this slideset can be
applied to other promises libraries like q or bluebird
Dominique Dumont $q promises
When is a promise needed ?
remote service call (Ajax call through $http service)
timer ($timeout service)
user interaction
wrap an old style API
Dominique Dumont $q promises
How to use a promise
$http.get('http://foo.com/')
.then(function(response) {
// extract data from response
return data;
})
.catch(function(error) {
// handle error, we'll see what to return later
})
.finally(function() {
$log.log(all done);
});
Dominique Dumont $q promises
then can be chained
Immediate calls:
var getData = $http.get('http://foo.com/')
.then(function(response) {
return $response.data.stuff;
})
.then(function(stuff) {
// do something with stuff
});
Dominique Dumont $q promises
then can be cascaded
Asynchronous calls:
var getData = $http.get('http://foo.com/')
.then(function(fooResponse) {
// need further remote request
// return a new promise
return $http.get('http://bar.com/');
})
.then(function(barResponse) {
// extract data
return data;
});
Dominique Dumont $q promises
then can throw error
var getData = $http.get('http://foo.com/')
.then(function(fooResponse) {
// $http call returned 200, but...
return $q.reject(I'm not happy);
});
Dominique Dumont $q promises
then summary
Promise callback can perform 3 types of treatment:
1 Immediate: return data
2 Asynchronous: return a new promise
3 Rejection: return $q.reject() with a message
Dominique Dumont $q promises
Error handling
then and catch behave like try and catch:
$http.get() // blow
.then(doA) // skip
.then(doB) // skip
.catch(cleanUp) // run
.then(doC) // run
.finally(allDone); // run
Dominique Dumont $q promises
Error handling
then and catch behave like try and catch:
$http.get() // ok
.then(doA) // $q.reject
.then(doB) // skip
.catch(cleanUp) // run
.then(doC) // run
.finally(allDone); // run
Dominique Dumont $q promises
Error handling
then and catch behave like try and catch:
$http.get() // blow
.then(doA) // skip
.then(doB) // skip
.catch(cleanUp) // blow
.then(doC) // skip
.finally(allDone); // run
nally() is run in all cases
Dominique Dumont $q promises
Concurrent promises
Anonymous:
$q.all([ getFoo, getBar ])
.then(function(res) {
var foo = res[0];
var bar = res[1];
});
Named:
$q.all({ 'foo': getFoo, 'bar': getBar ])
.then(function(res) {
var foo = res['foo'];
var bar = res['bar'];
});
Dominique Dumont $q promises
Concurrent promises
Anonymous:
$q.all([ getFoo, getBar ])
.then(function(res) {
var foo = res[0];
var bar = res[1];
});
Named:
$q.all({ 'foo': getFoo, 'bar': getBar ])
.then(function(res) {
var foo = res['foo'];
var bar = res['bar'];
});
Dominique Dumont $q promises
Concurrent promises and error handling
Any error is trapped in $q.all.catch():
var getFoo = $http.get(fooUrl).then(extract);
var getBar = $http.get(barUrl).then(extract);
$q.all({ 'foo': getFoo, 'bar': getBar })
.then(handleFooBar)
.catch(cleanUp); // receive data from failed promise
Dominique Dumont $q promises
Questions ?
Dominique Dumont $q promises

More Related Content

Similar to How to keep promises

CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
koji lin
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
tobiascrawley
 
Symfony 2 (PHP Quebec 2009)
Symfony 2 (PHP Quebec 2009)Symfony 2 (PHP Quebec 2009)
Symfony 2 (PHP Quebec 2009)
Fabien Potencier
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 

Similar to How to keep promises (20)

The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
 
I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Build service with_docker_in_90mins
Build service with_docker_in_90minsBuild service with_docker_in_90mins
Build service with_docker_in_90mins
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Symfony 2 (PHP Quebec 2009)
Symfony 2 (PHP Quebec 2009)Symfony 2 (PHP Quebec 2009)
Symfony 2 (PHP Quebec 2009)
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Symfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with easeSymfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with ease
 

More from Dominique Dumont

More from Dominique Dumont (8)

Quelques astuces pour débogguer Terraform.pdf
Quelques astuces pour débogguer Terraform.pdfQuelques astuces pour débogguer Terraform.pdf
Quelques astuces pour débogguer Terraform.pdf
 
Terraform - IAC - de quoi s'agit t'il ?.pdf
Terraform - IAC - de quoi s'agit t'il ?.pdfTerraform - IAC - de quoi s'agit t'il ?.pdf
Terraform - IAC - de quoi s'agit t'il ?.pdf
 
Démarrer avec Helm
Démarrer avec HelmDémarrer avec Helm
Démarrer avec Helm
 
Comment contribuer à un projet open source ?
Comment contribuer à un projet open source ?Comment contribuer à un projet open source ?
Comment contribuer à un projet open source ?
 
Cme: a tool to edit and validate configuration files
Cme: a tool to edit and validate configuration filesCme: a tool to edit and validate configuration files
Cme: a tool to edit and validate configuration files
 
The reports of Perl's death have been greatly exaggerated
The reports of Perl's death have been greatly exaggeratedThe reports of Perl's death have been greatly exaggerated
The reports of Perl's death have been greatly exaggerated
 
Magit
MagitMagit
Magit
 
kubernetes for beginners
kubernetes for beginnerskubernetes for beginners
kubernetes for beginners
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
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 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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+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)

%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
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 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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
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
 
%+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...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%+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...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 

How to keep promises

  • 1. $q: how to keep promises with AngularJS Dominique Dumont Apr 2018 Dominique Dumont $q promises
  • 2. What is a promise ? A way to write a function whose execution is deferred A way to trigger its execution on an external event Caveat This presentation was prepared in 2015 for Angular 1.5. Even if $q is obsolete now, the techniques shown in this slideset can be applied to other promises libraries like q or bluebird Dominique Dumont $q promises
  • 3. When is a promise needed ? remote service call (Ajax call through $http service) timer ($timeout service) user interaction wrap an old style API Dominique Dumont $q promises
  • 4. How to use a promise $http.get('http://foo.com/') .then(function(response) { // extract data from response return data; }) .catch(function(error) { // handle error, we'll see what to return later }) .finally(function() { $log.log(all done); }); Dominique Dumont $q promises
  • 5. then can be chained Immediate calls: var getData = $http.get('http://foo.com/') .then(function(response) { return $response.data.stuff; }) .then(function(stuff) { // do something with stuff }); Dominique Dumont $q promises
  • 6. then can be cascaded Asynchronous calls: var getData = $http.get('http://foo.com/') .then(function(fooResponse) { // need further remote request // return a new promise return $http.get('http://bar.com/'); }) .then(function(barResponse) { // extract data return data; }); Dominique Dumont $q promises
  • 7. then can throw error var getData = $http.get('http://foo.com/') .then(function(fooResponse) { // $http call returned 200, but... return $q.reject(I'm not happy); }); Dominique Dumont $q promises
  • 8. then summary Promise callback can perform 3 types of treatment: 1 Immediate: return data 2 Asynchronous: return a new promise 3 Rejection: return $q.reject() with a message Dominique Dumont $q promises
  • 9. Error handling then and catch behave like try and catch: $http.get() // blow .then(doA) // skip .then(doB) // skip .catch(cleanUp) // run .then(doC) // run .finally(allDone); // run Dominique Dumont $q promises
  • 10. Error handling then and catch behave like try and catch: $http.get() // ok .then(doA) // $q.reject .then(doB) // skip .catch(cleanUp) // run .then(doC) // run .finally(allDone); // run Dominique Dumont $q promises
  • 11. Error handling then and catch behave like try and catch: $http.get() // blow .then(doA) // skip .then(doB) // skip .catch(cleanUp) // blow .then(doC) // skip .finally(allDone); // run nally() is run in all cases Dominique Dumont $q promises
  • 12. Concurrent promises Anonymous: $q.all([ getFoo, getBar ]) .then(function(res) { var foo = res[0]; var bar = res[1]; }); Named: $q.all({ 'foo': getFoo, 'bar': getBar ]) .then(function(res) { var foo = res['foo']; var bar = res['bar']; }); Dominique Dumont $q promises
  • 13. Concurrent promises Anonymous: $q.all([ getFoo, getBar ]) .then(function(res) { var foo = res[0]; var bar = res[1]; }); Named: $q.all({ 'foo': getFoo, 'bar': getBar ]) .then(function(res) { var foo = res['foo']; var bar = res['bar']; }); Dominique Dumont $q promises
  • 14. Concurrent promises and error handling Any error is trapped in $q.all.catch(): var getFoo = $http.get(fooUrl).then(extract); var getBar = $http.get(barUrl).then(extract); $q.all({ 'foo': getFoo, 'bar': getBar }) .then(handleFooBar) .catch(cleanUp); // receive data from failed promise Dominique Dumont $q promises