[英]AngularJS : promises, can you pass a promise back after using .then()?
我還是Angular的新手並承諾所以我希望我在這里有正確的想法。
我目前有一個數據層服務,它使用restangular來獲取一些數據,然后返回一個promise,就像這樣......
dataStore.getUsers = function (params) {
return users.getList(params);
};
然后,我調用此函數的控制器會收到一個承諾,就像這樣......
$dataStore.getUsers(params).then(function (response) {
$scope.users = response;
}, function(response) {
$log.error("Get users returned an error: ", response);
});
這很好用,但我想在傳回數據存儲之前使用我的數據存儲區內的promise。 我想使用.then()方法檢查它是否失敗並進行一些日志記錄,然后,從sucess函數和失敗函數我想將原始的promise返回給我的控制器。
然后,我的控制器可以像現在一樣使用.then()方法,事實上,我不希望我的控制器代碼完全改變,只是我的數據存儲區代碼。
這里有一些半偽代碼來顯示我想要的數據存儲功能...
dataStore.getUsers = function (params) {
users.getList(params).then(function (response) {
$log("server responded")
return original promise;
}, function(response) {
$log.error("server did not respond");
return original promise;
});
};
你的偽代碼實際上並不遙遠。 承諾鏈:
dataStore.getUsers = function (params) {
return users.getList(params).then(function (response) {
$log("server responded")
return response;
}, function(failure) {
$log.error("server did not respond");
// change to throw if you want Angular lever logs
return $q.reject(failure);
});
};
控制器現在以相同的值被解析/拒絕。 日志需要訪問promise,因此您必須添加.then
處理程序來處理它。 其他承諾庫有相同的方法,但在這方面$ q是簡約的。
或者,您可以使用更好的catch語法,並將錯誤傳播到日志:
dataStore.getUsers = function (params) {
return users.getList(params).then(function (response) {
$log("server responded")
return response;
}).catch(function(failure) {
$log.error("server did not respond");
throw failure;
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.