如何使用promise chaining调用下一个错误函数?
我以为错误函数内部的返回会自动调用下一个错误函数。
//Called in a controller
dataService.saveRequest()
.then(function result(res){
//Logged when the service sends back a result
console.log("finished");
}, function error(error){
//Logged when the service sends back an error
//THIS DOES NOT GET CALLED
console.log("error from controller");
});
//INSIDE THE SERVICE
this.saveRequest = function(){
return $http.post('rest/request/send-request', someData)
.then(function(result){
//Goes, as expected, into the success function in the controller
return result.data;
}, function(error){
//Does NOT go into the next error function
//I need the error function to execute in the controller
return error;
});
};
答案 0 :(得分:2)
我很难在错误函数内部返回会自动调用下一个错误函数。
不,返回意味着您从错误情况中恢复,然后将解决成功回调。如果您从错误回调中返回并且想要将其传递给链中的下一个,则需要返回被拒绝的承诺:
dataService.saveRequest()
.then(function result(res) {
//Logged when the service sends back a result
console.log("finished");
}, function error(error) {
console.log("error from controller");
return $q.reject('error from controller');
});
或者代替或返回,你可以throw
。
答案 1 :(得分:1)
当您从处理程序返回值而不是Promise时,它会隐式包装Promise.resolve
。这也适用于拒绝处理程序,因此拒绝处理程序返回已解决的承诺。
您需要throw
或返回被拒绝的承诺以传播拒绝:
return $http.post('rest/request/send-request', someData)
.then(function(result){
//Goes, as expected, into the success function in the controller
return result.data;
}, function(error){
throw error;
});
答案 2 :(得分:1)
您必须从承诺返回return $q.reject();
,以便链中的下一个承诺也会失败。请参阅示例plunker:http://plnkr.co/edit/porOG8qVg2GkeddzVHu3?p=preview
原因是:您的错误处理程序可能会采取措施更正错误。在你的错误函数中你处理错误,如果没有另外指定,它将返回一个新的promise,它被解决。因此,默认情况下使下一个承诺失败是不合理的。把它想象成try / catch。
您正在捕获错误并对其进行处理 - 因此它会转到成功处理程序。如果你想拒绝它,你必须通过返回$ q.reject();
来做到这一点