[英]How to be explicit in resolving deferred promise in angular $q?
If I have something in my service
like 如果我有什么
service
myServiceMethod: function(){
$http.get(myUrl)
.success(function(result){$q.defer().resolve(result);})
.error(function(error){$q.defer().resolve(error);});
return $q.defer().promise;
}
and in my controller
在我的
controller
myService.myServiceMethod()
.then(function(result){})
.then(function(error){});
is there a way to be explicit in the name space? 有没有一种方法可以在名称空间中明确显示? Because it seems like the deferred promises can get messy if you start nesting deferred resolve.
因为如果您开始嵌套延迟的解析,似乎延迟的承诺可能会变得混乱。 For example
例如
myServiceMethod: function(){
$http.get(myUrl)
.success(
function(result){
if(result){
$q.defer().resolve(result);
}else{
$q.defer().resolve(myCustomresult);
}
})
.error(function(error){$q.defer().resolve(error);});
return $q.defer().promise;
}
You are creating too many deferred objects and the one being returned is not what you are resolving or rejecting 您创建了太多的延迟对象,而返回的对象不是您要解决或拒绝的对象
Just return the $http
which itself returns a promise. 只需返回
$http
本身就会返回一个承诺。 what you are trying to do is considered an anti-pattern 您尝试做的事情被认为是反模式
myServiceMethod: function(){
// return the `$http` promise
return $http.get(myUrl)
.then(function(result){return result.data);})
// either catch it here or catch in controller
.catch(function(error){ alert('Error')});
}
Controller 控制者
myService.myServiceMethod()
.then(function(result){})
.catch(function(error){});
Every time you call $q.defer() you are creating a new promise, which isn't the right thing to do. 每次调用$ q.defer()时,您都在创建一个新的Promise,这不是正确的选择。
The $http.get
method itself returns a promise, so unless you are doing something else that needs to run asynchronously, you do not need to use $q $http.get
方法本身会返回一个$http.get
,因此,除非您正在执行其他需要异步运行的操作,否则无需使用$ q
For arguments sake, you can do this: 出于参数考虑,您可以执行以下操作:
myServiceMethod: function() {
var myPromise = $q.defer();
$http.get(myUrl).success(function(result){
if(result)
myPromise.resolve(result);
else
myPromise.reject(result);
});
return myPromise.promise;
}
Could be much shorter: 可能更短:
Service 服务
myServiceMethod: function () {
return $http.get(myUrl).then(function (response) {
return response.data || myCustomResult; // default result if API returned nothing
});
}
Controller 控制者
myService.myServiceMethod()
.then(function (result) { /* do something ... */ })
.catch(function (error) { /* handle error ... */ });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.