How to abort a failing Q promise in Node.JS

天涯浪子 提交于 2019-12-12 04:14:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21821936/how-to-abort-a-failing-q-promise-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!