JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.0.1/q.js"></script>
console output
<pre id="log"></pre>
JavaScript
var out = document.getElementById('log');
var q = Q;
//failOn5();
altSyntax();
function failOn5() {
log('this chain has 7 steps, will fail on 5 and this skip 6 & 7\n')
step(0) // 1
.catch(errorHandeler)
.then(step) // 2
.catch(errorHandeler)
.then(step) // 3
.catch(errorHandeler)
.then(step) // 4
.catch(errorHandeler)
.then(failingStep) // 5 fail
.catch(errorHandeler)
.then(step) // 6
.catch(errorHandeler)
.then(step) // 7
.catch(errorHandeler)
.done(function(){
log('success arguments', arguments);
}, function(error) {
log('\nDone with failure \nerror.message="' + error.message + '"\n',error);
});
}
function altSyntax() {
log('this chain has 7 steps, will fail on 5 and this skip 6 & 7\n')
step(0) // 1
.catch()
.then(step,errorHandeler) // 2
.then(step,errorHandeler) // 3
.then(step,errorHandeler) // 4
.then(failingStep,errorHandeler) // 5 fail
.then(step,errorHandeler) // 6
.then(step,errorHandeler) // 7
.done(function(){
log('success arguments', arguments);
}, function(error) {
log('\nDone with failure \nerror.message="' + error.message + '"\n',error);
});
}
// a step that succeeds
function step(i) {
i++;
log('step ' + i);
return q.resolve(i);
}
// a step that fails
function failingStep(i) {
i++;
var e = new Error('failed on ' + i);
e.step = i;
log('step '+ e.step + ' (will fail)');
return q.reject(e);
}
// error handler
// when the error is passed for the first time
// the handle sets a property (breakChain)
// so that next calls just skip processing
// and continue rejecting which makes it look like
// we are breaking the chain
function errorHandeler(error) {
// if error has already been handled, pass
if (error.breakChain) {
log('errorHandeler: error.breakChain is true, rethrowing');
return q.reject(error);
}
// error is new;
error.breakChain = true;
log('errorHandler: caught error');
log('> error...