这是“递延反模式”吗?我发现很难理解“延迟反模式”。我想我在原则上理解它,但我还没有看到一个非常简单的服务例子,有着不同的承诺和反模式,所以我想我会尝试做我自己的,但考虑到我对它的了解不是很好,我会首先得到一些澄清。我在一家工厂里有以下情况://url = 'data.json';return {
getData: function(){
var deferred = $q.defer();
$http.get(destinationFactory.url)
.then(function (response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
return deferred.reject(response.data);
}
})
.catch(function (error) {
deferred.reject(error);
});
return deferred.promise;
}我之所以检查它是一个对象,只是为了将一个简单的验证层添加到$http.get()以下是我的指令:this.var = SomeFactory.getData()
.then(function(response) {
//some variable = response;
})
.catch(function(response) {
//Do error handling here});现在对我来说,这是一个反模式。因为最初的延迟承诺捕获了错误并简单地吞噬了它。它不返回错误,所以当调用这个“getData”方法时,我必须执行另一个捕获来获取错误。如果这不是反模式,那么有人能解释为什么两者都需要某种“回调”吗?当我第一次开始写这个工厂/指令的时候,我预料到必须在某个地方履行一个不遵守的承诺,但我并没有预料到.catch()在双方(也就是我的意思是,我想我可以让工厂返回响应或错误,如果我做了SomeFactory.getData()
3 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
这是“递延反模式”吗?
$http servicepromise
这是反模式 app.factory("SomeFactory",['$http','$q']){ return { getData: function(){ var deferred = $q.defer(); $http.get(destinationFactory.url) .then(function (response) { deferred.resolve(response.data); }) .catch(function (error) { deferred.reject(error); }); return deferred.promise; } }}])
app.factory("SomeFactory",['$http']){
return {
getData: function(){
//$http itself returns a promise
return $http.get(destinationFactory.url);
}}this.var = SomeFactory.getData()
.then(function(response) {
//some variable = response;
},function(response) {
//Do error handling here});
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
$q$q.when
var deferred = $q.defer();
$q.
return {
getData: function(){
return $http.get(destinationFactory.url)
.then(function (response) {
if (typeof response.data === 'object') {
return response.data;
} else {
throw new Error('Error message here');
}
});
// no need to catch and just re-throw
});
}- 3 回答
- 0 关注
- 566 浏览
添加回答
举报
0/150
提交
取消
