.success 和 .error 方法忽略返回值。
因此,它们不适合链接。
var httpPromise = $http
.get(/* some params */)
.success(function onSuccess(data, status, headers, config) {
var modifiedData = doModify(data);
//return value ignored
return modifiedData;
})
.error(function onError(data, status, headers, config) {
// error cases here
});
httpPromise.then(function onFullfilled(response) {
//chained data lost
//instead there is a response object
console.log(response.data); //original data
console.log(response.status); //original status
});
另一方面,.then 和.catch 方法返回一个派生的promise 适合链接返回(或抛出)的值或一个新的promise。
var derivedPromise = $http
.get(/* some params */)
.then(function onFulfilled(response) {
console.log(response.data); //original data
console.log(response.status); //original status
var modifiedData = doModify(response.data);
//return a value for chaining
return modifiedData;
})
.catch(function onRejected(response) {
// error cases here
});
derivedPromise.then(function onFullfilled(modifiedData) {
//data from chaining
console.log(modifiedData);
});
响应对象与四个参数
还要注意$http 服务在调用提供给.success 和.error 方法的函数时提供四个参数 (data, status, headers, config)。
$q 服务只为提供给.then 或.catch 方法的函数提供一个参数(响应)。对于由$http 服务创建的承诺,响应对象具有以下属性:1
- data – {string|Object} – 使用转换函数转换的响应正文。
- status – {number} – 响应的 HTTP 状态代码。
- headers – {function([headerName])} – Header getter 函数。
- config – {Object} – 用于生成请求的配置对象。
- statusText – {string} – 响应的 HTTP 状态文本。
链式承诺
因为调用 Promise 的 then 方法会返回一个新的派生 Promise,所以很容易创建一个 Promise 链。可以创建任意长度的链,并且由于可以使用另一个 Promise 来解决一个 Promise(这将进一步推迟其解决方案),因此可以在链中的任何点暂停/推迟对 Promise 的解决。这使得实现强大的 API 成为可能。2
更新
.success 和 .error 方法已被弃用并从 AngularJS V1.6 中删除。
有关详细信息,请参阅