-- 编辑 --
最近我遇到了一个关于 Promise 的奇怪问题,但我猜这可能是因为它违背了 Promise 的哲学。
考虑以下代码:
// Assuming Auth is just a simple lib doing http requests with promises
Auth.signup()
.then(succCall, errCall)
.then(loginSucc, loginErr)
// My callbacks here
function succCall (){
// OK, send second promise
console.log('succCall');
return Auth.login();
}
function errCall(){
// I do some things here and now
// I want to break out from here
console.log('errCall');
}
function loginSucc(){
// This is the callback of the login method when it went OK
// I want to enter here ONLY if with go through the succCall
console.log('loginSucc');
}
function loginErr(){
// This is the callback of the login method when it went not ok
// I want to enter here ONLY if with go through the succCall
console.log('loginErr');
}
如果Auth.signup()出现问题,会显示以下内容:
- errCall,loginSucc
如果在errCall中执行$q.reject(),下面是发生的情况:
- errCall,loginErr
这就是我想要的结果:
- errCall... 结束,停在这里
现在的问题是,当注册出错时,它进入了errCall,这很好,但接下来它进入了loginSucc...
当任何错误回调函数(在此为errCall或loginErr)被遇到时,我想要跳出“then”链。
--编辑--
我觉得有些人误解了我的意思,我想完全中断链,不希望在任何其他“then”中检查是否出现问题。
就像我说的:如果第一个“then”出现问题,停在这里;如果第一个“then”正常,则继续;如果第二个“then”正常,则继续;如果第三个“then”出现问题,则停止。
// Just like if i did the following but by chainning "then" methods
// My callbacks here
function succCall (){
// OK, send second promise
return Auth.login().then(loginSucc, loginErr);
}
我的意思是,如果我有许多“then”链接,我不希望只有一个错误处理程序。
catch
跳过您的errCall
和loginErr
函数,并将它们的逻辑放在catch
中。您将不得不查看catch
回调捕获的错误,但这是实现您想要的唯一方法。 - Adam JenkinsAuth.signup().then(succCall, errCall)
,succCall.then(loginSucc, loginErr)
,类似这样的。 - koox00