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