简体   繁体   中英

How to abort a failing Q promise in Node.JS

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM