Skip to content

Instantly share code, notes, and snippets.

@metamatt
Created February 3, 2015 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metamatt/766ecc70224c2b930809 to your computer and use it in GitHub Desktop.
Save metamatt/766ecc70224c2b930809 to your computer and use it in GitHub Desktop.
promise chaining in Q and angular $q
// find Q/$q implementation
var Q;
try {
$injector = angular.injector([ 'ng' ]);
Q = $injector.get('$q');
} catch (err) {
Q = require('q');
}
// helper function to attach handlers that show how promise is resolved
function attachHandlers(promise, name) {
promise.then(function(val) {
console.log('%s resolved as', name, val);
}).catch(function(err) {
console.log('%s errored as', name, err);
});
}
// Chain of 2 promises that resolve successfully
t1 = new Q.defer();
t2 = new Q.defer();
attachHandlers(t1.promise, 't1');
attachHandlers(t2.promise, 't2');
t2.resolve(t1.promise);
t1.resolve(42);
// Chain of 2 promises that resolve unsuccessfully
t1 = new Q.defer();
t2 = new Q.defer();
attachHandlers(t1.promise, 't1');
attachHandlers(t2.promise, 't2');
t2.resolve(t1.promise);
t1.reject('because');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment