Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active August 29, 2015 13:56
Show Gist options
  • Save brennanMKE/9311776 to your computer and use it in GitHub Desktop.
Save brennanMKE/9311776 to your computer and use it in GitHub Desktop.
Chaining promises with just a single error handler
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