Created
February 3, 2015 19:07
-
-
Save metamatt/766ecc70224c2b930809 to your computer and use it in GitHub Desktop.
promise chaining in Q and angular $q
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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