链接 javascript 承诺时,如何处理 then() 函数中的条件?

How do you handle conditions in then() functions when chaining javascript promises?

我正在处理 promises 并且需要弄清楚如何正确地链接它们,我理解如果 promises 在成功时解决并在错误时拒绝它是如何工作的,但是如果在其中一个之后可能出现错误状态怎么办承诺解决了吗?

这是我的场景

function getUser(userId){...} 
// resolves if user exist and (activated or not) returning user
// rejects to error1: user does not exist

function doTask(user){...}
// resolves on successful completion of the task
// rejects error3: could not do Task

如果我想用用户 ID 做另一个 promise do 任务怎么办,但前提是用户已激活

// function doTaskWithUserId(userId)
// reject to error1; user does not exist
// reject to error2; if user is not activated
// reject to error3; could not do task

这是我能做的,但如果我觉得我在搞砸某事;但这似乎是一个承诺反模式

function doTaskWithUserId(userId){
    var deffered = q.defer();
    getUser(userId)
    .then(function(user){
        if(user.activated === true){
            return doTask(user);
        }else{
            deffered.reject(error2); // user is not activated
        }
    }, function(){
        deffered.reject(error1);  // user does not exist
    })
    .then(function(){
        deffered.resolve(); // task complete
    }, function(){
        deffered.reject(error3) // could not do task
    })
    return deffered.promise;
}

似乎如果我这样做,外部承诺就会挂起,我已经阅读了 .fail() 和 .catch 方法,但似乎无法理解它们。任何帮助!谢谢

But this seems to be a promise anti-pattern

的确是: deferred antipattern! You don't need to construct a new deferred, you can just chain your actions, mappings and errors using then. You'll simply reject the returned promise 通过抛出:

function doTaskWithUserId(userId) {
    return getUser(userId).then(function(user) {
//  ^^^^^^
        if (user.activated) {
            return doTask(user);
        } else {
            throw error2; // user is not activated
        }
    }); // .then() returns a promise, which we return from the function
}