SlideShare 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

PPTX
Promises, Promises
PPTX
The Promised Land (in Angular)
PDF
JavaScript Promises
PPTX
JavaScript Promises
PDF
Promise pattern
PDF
Callbacks, promises, generators - asynchronous javascript
PPTX
Avoiding callback hell in Node js using promises
PDF
Asynchronous programming done right - Node.js
Promises, Promises
The Promised Land (in Angular)
JavaScript Promises
JavaScript Promises
Promise pattern
Callbacks, promises, generators - asynchronous javascript
Avoiding callback hell in Node js using promises
Asynchronous programming done right - Node.js

What's hot (20)

PDF
Getting Comfortable with JS Promises
PDF
JavaScript Promise
PDF
Javascript Promises/Q Library
PDF
JavaScript Promises
PDF
Practical JavaScript Promises
PPTX
Avoiding Callback Hell with Async.js
PPTX
Java Script Promise
PDF
Understanding Asynchronous JavaScript
PDF
Boom! Promises/A+ Was Born
PDF
JavaScript promise
PDF
Avoiding callback hell with promises
PDF
Callbacks and control flow in Node js
PPTX
Async Frontiers
PPTX
PDF
The evolution of asynchronous javascript
PPTX
ES6 is Nigh
PDF
Asynchronous Programming FTW! 2 (with AnyEvent)
PDF
Asynchronous programming patterns in Perl
PDF
How to send gzipped requests with boto3
PPTX
Build Lightweight Web Module
Getting Comfortable with JS Promises
JavaScript Promise
Javascript Promises/Q Library
JavaScript Promises
Practical JavaScript Promises
Avoiding Callback Hell with Async.js
Java Script Promise
Understanding Asynchronous JavaScript
Boom! Promises/A+ Was Born
JavaScript promise
Avoiding callback hell with promises
Callbacks and control flow in Node js
Async Frontiers
The evolution of asynchronous javascript
ES6 is Nigh
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous programming patterns in Perl
How to send gzipped requests with boto3
Build Lightweight Web Module
Ad

Similar to $q and Promises in AngularJS (20)

PPTX
What is Promise in Angular Development?
PPTX
Async discussion 9_29_15
ODP
Promises, The Tao of Angular
PPTX
Angular Promise vs Observable
PDF
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
PDF
Angular promises and http
PPT
You promise?
PDF
How to keep promises
PDF
JavaScript Promises Simplified [Free Meetup]
PPTX
Understanding Async/Await in Javascript
ZIP
Promises in JavaScript with jQuery
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
From Node.js to Design Patterns - BuildPiper
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
PDF
Asynchronous development in JavaScript
PDF
Javascript Promises
PDF
Asynchronous JavaScript Programming
PDF
The evolution of java script asynchronous calls
PPTX
Component-driven development with AngularJS
PDF
Async History - javascript
What is Promise in Angular Development?
Async discussion 9_29_15
Promises, The Tao of Angular
Angular Promise vs Observable
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Angular promises and http
You promise?
How to keep promises
JavaScript Promises Simplified [Free Meetup]
Understanding Async/Await in Javascript
Promises in JavaScript with jQuery
Async js - Nemetschek Presentaion @ HackBulgaria
From Node.js to Design Patterns - BuildPiper
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous development in JavaScript
Javascript Promises
Asynchronous JavaScript Programming
The evolution of java script asynchronous calls
Component-driven development with AngularJS
Async History - javascript
Ad

Recently uploaded (20)

PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PPT
JAVA ppt tutorial basics to learn java programming
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
Forouzan Book Information Security Chaper - 1
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
System and Network Administration Chapter 2
PPTX
How a Careem Clone App Allows You to Compete with Large Mobility Brands
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
PPTX
Benefits of DCCM for Genesys Contact Center
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Become an Agentblazer Champion Challenge
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
System and Network Administraation Chapter 3
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
JAVA ppt tutorial basics to learn java programming
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Forouzan Book Information Security Chaper - 1
The Role of Automation and AI in EHS Management for Data Centers.pdf
System and Network Administration Chapter 2
How a Careem Clone App Allows You to Compete with Large Mobility Brands
Which alternative to Crystal Reports is best for small or large businesses.pdf
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
Benefits of DCCM for Genesys Contact Center
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
Online Work Permit System for Fast Permit Processing
Become an Agentblazer Champion Challenge
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
System and Network Administraation Chapter 3
Best Practices for Rolling Out Competency Management Software.pdf
How to Migrate SBCGlobal Email to Yahoo Easily

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