dar*_*mnx 9 javascript promise angularjs angular-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');
}
Run Code Online (Sandbox Code Playgroud)
如果在Auth.signup()中出现问题,这就是显示:
如果我在errCall中执行$ q.reject(),则会发生以下情况:
这就是我想要的:
现在,问题是,当注册出错时,它会进入errCall,这很好,但随后它进入loginSucc ......
当遇到任何errorCallback(这是errCall或loginErr)时,我想突破当时的链.
- 编辑 -
我觉得我被某种意思误解了,我想彻底打破链条而不检查任何其他"然后"如果出现问题.
好像我在说:如果先错了就停在这里,如果先是然后确定继续,如果第二个"然后"确定继续,如果第三个"那么"错了,停止
// 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);
}
Run Code Online (Sandbox Code Playgroud)
我的观点是,如果我有很多"然后"链接,我不想只有一个错误处理程序
errCall函数需要返回一个 Promise,并且需要拒绝该 Promise 才能触发 loginErr。
function errCall(){
// i do some things here and now
return $q(function(resolve, reject) {
// auto reject
reject();
});
}
Run Code Online (Sandbox Code Playgroud)
或者尝试.catch:
Auth.signup()
.then(succCall)
.then(loginSucc)
.catch(function(err){
// caught error, problem is you won't know which function errored out, so you'll need to look at the error response
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
876 次 |
| 最近记录: |