這是“遞延反模式”嗎?我發現很難理解“延遲反模式”。我想我在原則上理解它,但我還沒有看到一個非常簡單的服務例子,有著不同的承諾和反模式,所以我想我會嘗試做我自己的,但考慮到我對它的了解不是很好,我會首先得到一些澄清。我在一家工廠里有以下情況://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 service
promise
這是反模式 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 關注
- 529 瀏覽
添加回答
舉報
0/150
提交
取消