SlideShare a Scribd company logo
1 of 28
Download to read offline
$q and Promises 
in AngularJS 
A. Sharif 
@sharifsbeat
Promises? 
Why even care?
Classic 
function getTShirt(callback) { 
setTimeout(function() { 
callback({'title' : 'superstar', price : 20}); 
}, 2000); 
} 
function getItem(item) { 
console.log(item); 
} 
// call getTShirt with a callback... 
getTShirt(getItem);
Classic 
function getCd(callback) { 
setTimeout(function() { 
callback({'title' : 'limited Edition', price : 30}); 
}, 4000); 
} 
What if we need to call getCd and getTShirt?
Classic 
function getCd(callback) { 
setTimeout(function() { 
callback({'title' : 'limited Edition', price : 30}); 
}, 4000); 
} 
What if we need to call getCd and getTShirt? 
getCd(function(cd) { 
getTShirt(function(tShirt) { 
getSomeDifferentItem(function(differentItem) { 
// things get complicated... 
}); 
}); 
});
There is a better way...
“A promise in short: is the future result 
of an operation or a placeholder for a 
successful result or an error”
Promises 
• No need for Callbacks to handle async operations 
• Compose multiple operations and have them run 
sequential or even in parallel 
• Dynamically add promises 
• Simulate try/catch 
• Readable code 
• Q, when.js, Bluebird, ES6 promises
Promises... 
The AngularJS way
$q 
• Light weight implementation of Q (Kris Kowal) 
• $http, $routeProvider and $timeout all use promises 
(you probably have been using promises all the time) 
• Differentiate between sender and receiver 
(Deferred and Promise) 
• Tightly interwoven with $rootScope.scope
The Deferred API 
• A new instance is created via: $q.defer() 
• Is used to expose the promise and signal success, 
failure or status of a task 
• Methods: resolve, reject, notify 
• Access the promise via the promise property 
• Promise can either be resolved or rejected once
The Deferred API 
Return a promise - remove the callback 
function getTShirt() { 
var deferred = $q.defer(); 
setTimeout(function() { 
deferred.resolve({'title' : 'superstar', price : 20}); 
}, 2000); 
return deferred.promise; 
}
The Promise API 
var tShirtOrder = getTShirt(); 
// tShirtOrder will not have the expected result 
console.log(tShirtOrder);
The Promise API 
getTshirt() 
.then( 
// on success... 
function(result) { 
console.log(result); 
}, 
// on failure... 
function(errorMsg) { 
console.log( errorMsg); 
}, 
// notify... 
function(percentage) { 
console.log(percentage); 
} 
);
The Promise API 
• Powerful for chaining promises via .then() 
• The ability to handle multiple asynchronous calls 
sequentially 
• Especially useful when one operation depends on 
information from another operation (f.e. a rest call 
depending on information from another rest call)
The Promise API 
getTshirt() 
.then(function(result) { 
// f.e. $scope.orders.push(result); 
return getCd(); 
}) 
.then(function(result) { 
return result; 
}) 
.then(function(result) { 
... 
}); 
Use .then() to chain promises
The Promise API 
Use catch and finally to cover all possible outcomes 
// will be called as soon as an exception 
// or failure happens further up the chain 
.catch(function(errorMsg) { 
console.log(errorMsg); 
}) 
// use for cleanup actions... 
.finally(function() { 
console.log('This will always be called...'); 
});
The Promise API 
What if a promise has been resolved already? 
// the callback will be called via the next digest loop 
promise.then(callback);
There is more...
$q.all() 
• Handling multiple promises (Parallel) 
• $q.all resolves when all promises have been 
successfully resolved 
• $q.all rejects as soon as one promise has been 
rejected, returning an error message. 
• Instead of using $scope.$watch to find out when 
information has been loaded
$q.all() 
var promiseA = $http.get('path/one'); 
var promiseB = $http.get('path/two'); 
var promiseC = $http.get('path/three'); 
$q.all([promiseA, promiseB, promiseC]) 
.then(function(results) { 
console.log(results[0], results[1], results[2]); 
});
$q.all() 
Alternatively define an object and access the results 
via properties 
$q.all({a: promiseA, b: promiseB, c: promiseC}) 
.then(function(results) { 
console.log(results.a, results.b, results.c); 
});
$q.all() 
var promiseCollection = []; 
promiseCollection.push(getTShirt()); 
if (hasCdOrder) { 
promiseCollection.push(getCd()); 
} 
$q.all(promiseCollection) 
.then(function(results) { 
console.log(results); 
}); 
Dynamically add a promise
There is even more...
$q.when() 
• When dealing with objects that might or might not 
be a promise 
• Third party promises 
• Source that can not be trusted 
• Wraps anything into a $q promise 
• If not a promise it will be automatically resolved
$q.when() 
var promiseOrNot = $q.when(mightBeAPromise); 
$q.all([promiseOrNot, getTshirt(), getCd()]) 
.then(function(result) { 
console.log(result); 
});
Thank You. 
@sharifsbeat

More Related Content

What's hot

Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script PromiseAlok Guha
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was BornDomenic Denicola
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promisesTorontoNodeJS
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)xSawyer
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perldeepfountainconsulting
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3Luciano Mammino
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 

What's hot (20)

Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
Domains!
Domains!Domains!
Domains!
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 

Similar to $q and Promises in AngularJS

AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
A real-world example of Functional Programming with fp-ts - no experience req...
A real-world example of Functional Programming with fp-ts - no experience req...A real-world example of Functional Programming with fp-ts - no experience req...
A real-world example of Functional Programming with fp-ts - no experience req...Frederick Fogerty
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
When symfony met promises
When symfony met promises When symfony met promises
When symfony met promises Marc Morera
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS developmentRomanPanichkin
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-sagaYounes (omar) Meliani
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflowAlex Alexeev
 
Creating an Uber Clone - Part XV.pdf
Creating an Uber Clone - Part XV.pdfCreating an Uber Clone - Part XV.pdf
Creating an Uber Clone - Part XV.pdfShaiAlmog1
 
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
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 

Similar to $q and Promises in AngularJS (20)

AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Promises & limbo
Promises & limboPromises & limbo
Promises & limbo
 
A real-world example of Functional Programming with fp-ts - no experience req...
A real-world example of Functional Programming with fp-ts - no experience req...A real-world example of Functional Programming with fp-ts - no experience req...
A real-world example of Functional Programming with fp-ts - no experience req...
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
When symfony met promises
When symfony met promises When symfony met promises
When symfony met promises
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS development
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
 
Creating an Uber Clone - Part XV.pdf
Creating an Uber Clone - Part XV.pdfCreating an Uber Clone - Part XV.pdf
Creating an Uber Clone - Part XV.pdf
 
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
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 

Recently uploaded

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
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
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
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
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
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
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
 
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
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
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
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
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)

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
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.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
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
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
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
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
 
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
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
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
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

$q and Promises in AngularJS

  • 1. $q and Promises in AngularJS A. Sharif @sharifsbeat
  • 3. Classic function getTShirt(callback) { setTimeout(function() { callback({'title' : 'superstar', price : 20}); }, 2000); } function getItem(item) { console.log(item); } // call getTShirt with a callback... getTShirt(getItem);
  • 4. Classic function getCd(callback) { setTimeout(function() { callback({'title' : 'limited Edition', price : 30}); }, 4000); } What if we need to call getCd and getTShirt?
  • 5. Classic function getCd(callback) { setTimeout(function() { callback({'title' : 'limited Edition', price : 30}); }, 4000); } What if we need to call getCd and getTShirt? getCd(function(cd) { getTShirt(function(tShirt) { getSomeDifferentItem(function(differentItem) { // things get complicated... }); }); });
  • 6. There is a better way...
  • 7. “A promise in short: is the future result of an operation or a placeholder for a successful result or an error”
  • 8. Promises • No need for Callbacks to handle async operations • Compose multiple operations and have them run sequential or even in parallel • Dynamically add promises • Simulate try/catch • Readable code • Q, when.js, Bluebird, ES6 promises
  • 10. $q • Light weight implementation of Q (Kris Kowal) • $http, $routeProvider and $timeout all use promises (you probably have been using promises all the time) • Differentiate between sender and receiver (Deferred and Promise) • Tightly interwoven with $rootScope.scope
  • 11. The Deferred API • A new instance is created via: $q.defer() • Is used to expose the promise and signal success, failure or status of a task • Methods: resolve, reject, notify • Access the promise via the promise property • Promise can either be resolved or rejected once
  • 12. The Deferred API Return a promise - remove the callback function getTShirt() { var deferred = $q.defer(); setTimeout(function() { deferred.resolve({'title' : 'superstar', price : 20}); }, 2000); return deferred.promise; }
  • 13. The Promise API var tShirtOrder = getTShirt(); // tShirtOrder will not have the expected result console.log(tShirtOrder);
  • 14. The Promise API getTshirt() .then( // on success... function(result) { console.log(result); }, // on failure... function(errorMsg) { console.log( errorMsg); }, // notify... function(percentage) { console.log(percentage); } );
  • 15. The Promise API • Powerful for chaining promises via .then() • The ability to handle multiple asynchronous calls sequentially • Especially useful when one operation depends on information from another operation (f.e. a rest call depending on information from another rest call)
  • 16. The Promise API getTshirt() .then(function(result) { // f.e. $scope.orders.push(result); return getCd(); }) .then(function(result) { return result; }) .then(function(result) { ... }); Use .then() to chain promises
  • 17. The Promise API Use catch and finally to cover all possible outcomes // will be called as soon as an exception // or failure happens further up the chain .catch(function(errorMsg) { console.log(errorMsg); }) // use for cleanup actions... .finally(function() { console.log('This will always be called...'); });
  • 18. The Promise API What if a promise has been resolved already? // the callback will be called via the next digest loop promise.then(callback);
  • 20. $q.all() • Handling multiple promises (Parallel) • $q.all resolves when all promises have been successfully resolved • $q.all rejects as soon as one promise has been rejected, returning an error message. • Instead of using $scope.$watch to find out when information has been loaded
  • 21. $q.all() var promiseA = $http.get('path/one'); var promiseB = $http.get('path/two'); var promiseC = $http.get('path/three'); $q.all([promiseA, promiseB, promiseC]) .then(function(results) { console.log(results[0], results[1], results[2]); });
  • 22. $q.all() Alternatively define an object and access the results via properties $q.all({a: promiseA, b: promiseB, c: promiseC}) .then(function(results) { console.log(results.a, results.b, results.c); });
  • 23. $q.all() var promiseCollection = []; promiseCollection.push(getTShirt()); if (hasCdOrder) { promiseCollection.push(getCd()); } $q.all(promiseCollection) .then(function(results) { console.log(results); }); Dynamically add a promise
  • 24. There is even more...
  • 25. $q.when() • When dealing with objects that might or might not be a promise • Third party promises • Source that can not be trusted • Wraps anything into a $q promise • If not a promise it will be automatically resolved
  • 26. $q.when() var promiseOrNot = $q.when(mightBeAPromise); $q.all([promiseOrNot, getTshirt(), getCd()]) .then(function(result) { console.log(result); });
  • 27.