Skip to content

Instantly share code, notes, and snippets.

@staltz
Last active August 29, 2015 14:00
Show Gist options
  • Save staltz/28d521a428505860132b to your computer and use it in GitHub Desktop.
Save staltz/28d521a428505860132b to your computer and use it in GitHub Desktop.
Q promises point-wise error handling
var Q = require('q');
function delaydo(x) {
var deferred = Q.defer();
setTimeout(function() {
if (x === 2) {
console.log("reject: "+x);
deferred.reject(x);
}
else {
console.log("resolve: "+x);
deferred.resolve(x);
}
}, 1000);
return deferred.promise;
}
delaydo(1)
.then(function() {
return delaydo(2);
}, function(err) {
console.log("Error handler A: "+err);
})
.then(function() {
return delaydo(3);
}, function(err) {
console.log("Error handler B: "+err);
})
.then(function() {
return delaydo(4);
}, function(err) {
console.log("Error handler C: "+err);
})
.catch(function(err) {
console.log("Caught err: "+err);
});
resolve: 1
reject: 2
Error handler B: 2
resolve: 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment