Let's say I'm building a registration flow, and I have something that looks like this:
Q.nfcall(validateNewRegCallback, email, password)
.fail(function(err){
console.log("bad email/pass: " + err);
return null;
})
.then(function(){
console.log("Validated!");
})
.done();
If my registration fails, I'd like to catch it, and die. Instead, I see both "bad email/pass" and "validated". Why is that, and how can I abort in the first failure call?
The fail
handler does catch rejected promises, but then does return a fulfilled promise (with null
in your case), as the error was handled already…
So what can you do against this?
Re-throw the error to reject the returned promise. It will cause the done
to throw it.
Q.nfcall(validateNewRegCallback, email, password).fail(function(err){
console.log("bad email/pass: " + err);
throw err;
}).then(function(){
console.log("Validated!");
}).done();
Handle the error after the success callback (which also handles errors in the success callback):
Q.nfcall(validateNewRegCallback, email, password).then(function(){
console.log("Validated!");
}).fail(function(err){
console.log("bad email/pass: " + err);
}).done();
Simply handle both cases on the same promise - every method does accept two callbacks:
Q.nfcall(validateNewRegCallback, email, password).done(function(){
console.log("Validated!");
}, function(err){
console.log("bad email/pass: " + err);
};
You also might use .then(…, …).done()
of course.