Last active
August 29, 2015 13:56
-
-
Save brennanMKE/9311776 to your computer and use it in GitHub Desktop.
Chaining promises with just a single error handler
This file contains 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
var Promise = require('promise'); | |
var limit = 3; | |
var doAsync = function(nbr) { | |
var promise = new Promise(function (resolve, reject) { | |
setTimeout(function() { | |
if (nbr <= limit) { | |
// increment the given value by 1 | |
resolve(nbr+1); | |
} | |
else { | |
// reject the promise if nbr is over the limit | |
reject('Number is over limit: ' + nbr); | |
} | |
}, 10); | |
}); | |
return promise; | |
}; | |
var handleSuccess = function(result) { | |
console.log('Success: ' + result); | |
}; | |
var handleError = function(error) { | |
console.log('Error: ' + error); | |
}; | |
// each call to doAsync increments the value by 1 | |
// then is passed to the next step in the chain | |
doAsync(0).then(doAsync). | |
then(doAsync). | |
then(doAsync). | |
then(doAsync). | |
then(doAsync). | |
then(doAsync). | |
then(doAsync). | |
then(handleSuccess, handleError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment