如果我有很长的承诺链,那么后端可能会提供某些不正确的逻辑。例如,我试图把车放在车库里。有些车库不能装卡车。其他一些车库的大小足以容纳卡车,因此我们不想在那里放置普通车。和程序示例:
我可以以某种方式忽略链的其余部分并执行
somethingIsWrong(violations);
而不是通过承诺链而拒绝所有。
var promise = firstCall();
promise.then( function(){
secondCall();
}, error, notify
)
.then(
function(params) {
var def = $q.defer();
return getViolations(params)
.then(
function(violations){
if(violations.length==0){
//OK
def.resolve(params);
} else {
return $q.reject("violations triggered");
// ideally here would be this:
//somethingIsWrong(violations);
}
return def.promise;
},
function(errMsg) { // errorCallback
return $q.reject(errMsg);
},
function() { /*notifyCallback*/ }
)
},
function(errMsg) { // errorCallback
return $q.reject(errMsg);
},
function() { /*notifyCallback*/ }
)
// Here may be n number of .then() calls while resolving all necessary data of cars and garages.
.then(
function(updateset) {
log("YEAH SUCCESS");
},
function(errMsg) { // errorCallback
//For now we deal this with a pop-up, but possible will do some thing else
window.alert('Violations triggered:\n\n' + errMsg);
},
function() { /*notifyCallback */ }
);
--- --- EDIT
最后,我得到了类似的结果:
var promise = firstCall();
promise.then( function(){
secondCall();
}, error
)
.then(
function(params) {
return getViolations(params)
.then(
function(violations){
if(violations.length==0){
//OK
return restOfTheSuccessfulRun(params);
} else {
return $q.reject("violations triggered");
// ideally here would be this:
return somethingIsWrong(violations);
}
},
function(errMsg) { // errorCallback
return $q.reject(errMsg);
}
)
},
function(errMsg) { // errorCallback
return $q.reject(errMsg);
}
);
function restOfTheSuccessfulRun(params) {
asyncCallsNTimes(params)
// Here may be n number of .then() calls while resolving all necessary data of cars and garages.
.then(
function(updateset) {
log("YEAH SUCCESS");
},
function(errMsg) { // errorCallback
//For now we deal this with a pop-up, but possible will do some thing else
window.alert('Violations triggered:\n\n' + errMsg);
}
)
}
function somethingIsWrong(violations) {
var response;
//handle violations
return response;
}
另外,我想补充一点,如果你需要调用它5次来执行一个动作,你的设计设计很糟糕。但是,如果你不能再影响它,那么这可能是一个好方法。换句话说,当你的承诺链中途,你需要根据你将如何继续到最后的一个回答做出决定。并且两个方向都是有效的(不是常规错误/承诺错误处理)。