关于官方文档中的$ http:
$ http API基于$ q服务公开的延迟/承诺API。
$ http服务是一个带有单个参数(配置对象)的函数,该参数用于生成HTTP请求并返回承诺
那么下面的代码是什么意思:
var deferred = $q.defer();
var promise = deferred.promise;
var progress;
$http.get("https://api.github.com/repos/angular/angular.js/pulls")
.success(function(data){
var result = [];
for(var i = 0; i < data.length; i++){
result.push(data[i].user);
progress = (i+1)/data.length * 100;
deferred.notify(progress);
}
deferred.resolve(result);
})
.error(function(error){
deferred.reject(error);
});
return promise;
如果$ http返回一个承诺,为什么我应该使用$ q来返回一个承诺?
推荐的$http
服务使用方式如下:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// success code here
}, function errorCallback(response) {
// error handling code here
});
在这种情况下,您不必返回新的Promise,而只需将调用的结果返回给then()
您期望的即可。
但是,该success()
方法是一种便捷方法,已经将响应对象的字段作为单独的参数传递给了:
.then(function(response) {
// do something with response.data, response.status, etc.
})
与
.success(function(data, status, headers, config) {
// do something with data, status, etc.
})
但是,与相比then()
,success()
不会返回承诺。我不建议使用它,而我只是在docs中看到,到目前为止它已被弃用。
更新:我认为您提供的示例中构造了另一个promise的原因不是success()
可以使用而是可以调用deferred.notify(progress)
。如果没有显式创建另一个promise,您将无权访问该deferred
对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句