我正在使用promises并且需要弄清楚如何正确地链接它们,我理解如果promises成功解决并拒绝错误,它是如何工作的,但是如果在一个promise之后可能存在错误状态怎么办?解决?
这是我的场景
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的任务,但仅当用户被激活时
// 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方法,但似乎可以绕过它们。一切都有帮助!感谢
答案 0 :(得分:4)
确实如此:deferred antipattern!您不需要构建新的延迟,您可以使用但这似乎是一种承诺反模式
then
just chain您的操作,映射和错误。您只需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
}