.then 返回一个新的承诺。
.success 返回原始承诺。另一个区别是.success 获取response.data 作为输入参数,而.then 获取response。
这是how it's implemented:
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
您可以使用.success(和.error)来处理$http 的相应结果,但不能修改数据或拒绝给予最终消费者的承诺(使用return $q.reject()) $http 承诺。
这是一个说明性示例,说明何时可以使用 .success vs/with .then:
return {
getData: function(p1){
return $http.get(url, {p1: p1})
.success($log.log) // can use generic functions since there is
.error($log.error) // no requirement to return data
.then(function(response){
// here can massage the data into the output format
return response.data;
});
};
我建议始终使用.then,因为它返回一个没有.success 和.error 处理程序的新承诺;这避免了 API 使用者使用 $http 特定的 .success/.error 的机会,从而无意中假设 $http 在幕后使用。