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 Keep Promises with AngularJS $q

The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHPWim Godden
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuturekoji lin
 
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)Robert Lemke
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
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 pagessparkfabrik
 
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.pdfLuca Lusso
 
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)xsist10
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Build service with_docker_in_90mins
Build service with_docker_in_90minsBuild service with_docker_in_90mins
Build service with_docker_in_90minsLarry Cai
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
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 tuningAOE
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
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 easeOscar Merida
 

Similar to Keep Promises with AngularJS $q (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
 
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
 
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
 
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

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.pdfDominique Dumont
 
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 ?.pdfDominique Dumont
 
Comment contribuer à un projet open source ?
Comment contribuer à un projet open source ?Comment contribuer à un projet open source ?
Comment contribuer à un projet open source ?Dominique Dumont
 
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 filesDominique Dumont
 
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 exaggeratedDominique 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

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

Keep Promises with AngularJS $q

  • 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