ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
$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); 
});
$q and Promises in AngularJS
Thank You. 
@sharifsbeat

More Related Content

What's hot (20)

Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
?
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
Joseph Chiang
?
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
?
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
?
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
?
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
?
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
?
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
?
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
?
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
?
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
?
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
Thomas Roch
?
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
Domenic Denicola
?
Domains!
Domains!Domains!
Domains!
Domenic Denicola
?
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
?
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
?
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 Perl
deepfountainconsulting
?
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
Luciano Mammino
?
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
?
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
?
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
?
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
?
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
?
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
?
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
?
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
?
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
?
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
Thomas 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 Perl
deepfountainconsulting
?
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
Luciano Mammino
?
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
?

Similar to $q and Promises in AngularJS (20)

AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
Gaurav Behere
?
Promises & limbo
Promises & limboPromises & limbo
Promises & limbo
Sylvain Faucherand
?
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: Functions
Adam Crabtree
?
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique 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 development
RomanPanichkin
?
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio 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-saga
Younes (omar) Meliani
?
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
?
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
?
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
?
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
?
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
?
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
Taketoshi ÇàÒ°½¡Àû
?
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
Alex 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.pdf
ShaiAlmog1
?
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
Codemotion
?
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
Nicolas Quiceno Benavides
?
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
Seok-joon Yun
?
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: Functions
Adam Crabtree
?
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique 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 development
RomanPanichkin
?
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio 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-saga
Younes (omar) Meliani
?
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
?
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
?
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
?
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
·ÇͬÆÚÂá²¹±¹²¹²õ³¦°ù¾±±è³Ù¤Î¹ýÈ¥¤ÈδÀ´
Taketoshi ÇàÒ°½¡Àû
?
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
Alex 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.pdf
ShaiAlmog1
?
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
Codemotion
?
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
Seok-joon Yun
?

Recently uploaded (20)

Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
OnePlan Solutions
?
DORA Community - Building 10x Development Organizations.pdf
DORA Community - Building 10x Development Organizations.pdfDORA Community - Building 10x Development Organizations.pdf
DORA Community - Building 10x Development Organizations.pdf
Justin Reock
?
CSI SAP2000 Ultimate Crack 2025 Free Download
CSI SAP2000 Ultimate Crack 2025 Free DownloadCSI SAP2000 Ultimate Crack 2025 Free Download
CSI SAP2000 Ultimate Crack 2025 Free Download
raoufsomroo2021kp
?
OSN-Blazingly Fast GenAI App Development With Java and Spring AI
OSN-Blazingly Fast GenAI App Development With Java and Spring AIOSN-Blazingly Fast GenAI App Development With Java and Spring AI
OSN-Blazingly Fast GenAI App Development With Java and Spring AI
Juarez Junior
?
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdfDevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
Juarez Junior
?
Data structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptxData structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptx
itzsomeone50
?
LLM-based Multi-Agent Systems to Replace Traditional Software
LLM-based Multi-Agent Systems to Replace Traditional SoftwareLLM-based Multi-Agent Systems to Replace Traditional Software
LLM-based Multi-Agent Systems to Replace Traditional Software
Ivo Andreev
?
AI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
AI/ML Infra Meetup | How Uber Optimizes LLM Training and FinetuneAI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
AI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
Alluxio, Inc.
?
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber ScaleAI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
Alluxio, Inc.
?
Deploying to production with confidence ?
Deploying to production with confidence ?Deploying to production with confidence ?
Deploying to production with confidence ?
Andres Almiray
?
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Shubham Joshi
?
Agentic AI: The Future of Intelligent Automation
Agentic AI: The Future of Intelligent AutomationAgentic AI: The Future of Intelligent Automation
Agentic AI: The Future of Intelligent Automation
AutomationEdge Technologies
?
Lecture No asfasf 07 cloud computing.pptx
Lecture No asfasf 07 cloud computing.pptxLecture No asfasf 07 cloud computing.pptx
Lecture No asfasf 07 cloud computing.pptx
2423551
?
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
Alluxio, Inc.
?
sensor_tower__state_of_mobile_2025__Vietnam.pdf
sensor_tower__state_of_mobile_2025__Vietnam.pdfsensor_tower__state_of_mobile_2025__Vietnam.pdf
sensor_tower__state_of_mobile_2025__Vietnam.pdf
AnhTrnQunh6
?
The Future of Work How Digital Workplace Technologies Enhance Productivity
The Future of Work How Digital Workplace Technologies Enhance ProductivityThe Future of Work How Digital Workplace Technologies Enhance Productivity
The Future of Work How Digital Workplace Technologies Enhance Productivity
InfinCE Cloud
?
Wondershare Recoverit 13.0.1.6 Crack Free Download
Wondershare Recoverit 13.0.1.6 Crack Free DownloadWondershare Recoverit 13.0.1.6 Crack Free Download
Wondershare Recoverit 13.0.1.6 Crack Free Download
jrehmani658
?
Toon Boom Harmony Premium Crack Activation Key
Toon Boom Harmony Premium Crack Activation KeyToon Boom Harmony Premium Crack Activation Key
Toon Boom Harmony Premium Crack Activation Key
raffayihan9
?
Windows Movie Maker 2025 Crack + Registration Code Free Download
Windows Movie Maker 2025 Crack + Registration Code Free DownloadWindows Movie Maker 2025 Crack + Registration Code Free Download
Windows Movie Maker 2025 Crack + Registration Code Free Download
ca6725722
?
AIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
AIThe Rise of AI Twins: How Digital Twins Are Changing Business StrategyAIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
AIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
asmith539880
?
Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
Fixing Project Portfolio Visibilit: How to Get Real-Time Insights for Better ...
OnePlan Solutions
?
DORA Community - Building 10x Development Organizations.pdf
DORA Community - Building 10x Development Organizations.pdfDORA Community - Building 10x Development Organizations.pdf
DORA Community - Building 10x Development Organizations.pdf
Justin Reock
?
CSI SAP2000 Ultimate Crack 2025 Free Download
CSI SAP2000 Ultimate Crack 2025 Free DownloadCSI SAP2000 Ultimate Crack 2025 Free Download
CSI SAP2000 Ultimate Crack 2025 Free Download
raoufsomroo2021kp
?
OSN-Blazingly Fast GenAI App Development With Java and Spring AI
OSN-Blazingly Fast GenAI App Development With Java and Spring AIOSN-Blazingly Fast GenAI App Development With Java and Spring AI
OSN-Blazingly Fast GenAI App Development With Java and Spring AI
Juarez Junior
?
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdfDevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
DevTalks Cluj Romania - A Solid Foundation for GenAI Apps.pdf
Juarez Junior
?
Data structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptxData structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptx
itzsomeone50
?
LLM-based Multi-Agent Systems to Replace Traditional Software
LLM-based Multi-Agent Systems to Replace Traditional SoftwareLLM-based Multi-Agent Systems to Replace Traditional Software
LLM-based Multi-Agent Systems to Replace Traditional Software
Ivo Andreev
?
AI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
AI/ML Infra Meetup | How Uber Optimizes LLM Training and FinetuneAI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
AI/ML Infra Meetup | How Uber Optimizes LLM Training and Finetune
Alluxio, Inc.
?
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber ScaleAI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
AI/ML Infra Meetup | Deployment, Discovery and Serving of LLMs at Uber Scale
Alluxio, Inc.
?
Deploying to production with confidence ?
Deploying to production with confidence ?Deploying to production with confidence ?
Deploying to production with confidence ?
Andres Almiray
?
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Bug Life Cycle in Software Testing: Understanding the Journey from Detection ...
Shubham Joshi
?
Lecture No asfasf 07 cloud computing.pptx
Lecture No asfasf 07 cloud computing.pptxLecture No asfasf 07 cloud computing.pptx
Lecture No asfasf 07 cloud computing.pptx
2423551
?
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
AI/ML Infra Meetup | Building Production Platform for Large-Scale Recommendat...
Alluxio, Inc.
?
sensor_tower__state_of_mobile_2025__Vietnam.pdf
sensor_tower__state_of_mobile_2025__Vietnam.pdfsensor_tower__state_of_mobile_2025__Vietnam.pdf
sensor_tower__state_of_mobile_2025__Vietnam.pdf
AnhTrnQunh6
?
The Future of Work How Digital Workplace Technologies Enhance Productivity
The Future of Work How Digital Workplace Technologies Enhance ProductivityThe Future of Work How Digital Workplace Technologies Enhance Productivity
The Future of Work How Digital Workplace Technologies Enhance Productivity
InfinCE Cloud
?
Wondershare Recoverit 13.0.1.6 Crack Free Download
Wondershare Recoverit 13.0.1.6 Crack Free DownloadWondershare Recoverit 13.0.1.6 Crack Free Download
Wondershare Recoverit 13.0.1.6 Crack Free Download
jrehmani658
?
Toon Boom Harmony Premium Crack Activation Key
Toon Boom Harmony Premium Crack Activation KeyToon Boom Harmony Premium Crack Activation Key
Toon Boom Harmony Premium Crack Activation Key
raffayihan9
?
Windows Movie Maker 2025 Crack + Registration Code Free Download
Windows Movie Maker 2025 Crack + Registration Code Free DownloadWindows Movie Maker 2025 Crack + Registration Code Free Download
Windows Movie Maker 2025 Crack + Registration Code Free Download
ca6725722
?
AIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
AIThe Rise of AI Twins: How Digital Twins Are Changing Business StrategyAIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
AIThe Rise of AI Twins: How Digital Twins Are Changing Business Strategy
asmith539880
?

$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); });