为什么承诺的回调是反模式的?我在StackOverflow上看到了答案,人们建议为AngularJS服务提供回调函数。app.controller('tokenCtrl', function($scope, tokenService) {
tokenService.getTokens(function callbackFn(tokens) {
$scope.tokens = tokens;
});});app.factory('tokenService', function($http) {
var getTokens = function(callbackFn) {
$http.get('/api/tokens').then (function onFulfilled(response) {
callbackFn(response.data);
});
};
return {
getTokens: getTokens };});在我看来,这是一种反模式。这个$http服务返回承诺.then方法执行回调函数感觉就像不健康的控制反转。如何再因素这样的代码,以及如何解释为什么最初的方法是不是个好主意?
3 回答
aluckdog
TA贡献1847条经验 获得超7个赞
var getTokens = function() {
return $http.get('/api/tokens');
};yourModule.getTokens()
.then(function(response) {
// handle it
});
子衿沉夜
TA贡献1828条经验 获得超3个赞
app.controller('tokenCtrl', function($scope, tokenService) {
tokenService.getTokens.then ( callbackFn(tokens) {
$scope.tokens = tokens;
});});app.factory('tokenService', function($http) {
var getTokens = function() {
//return promise
return $http.get('/api/tokens').then (function onFulfilled(response) {
//return tokens
return response.data;
}
);
};
return {
getTokens: getTokens };});.then
承诺可以被拯救并用于 链子.可以保存承诺并使用它来避免重复相同的承诺。 $http打电话。 错误信息被保留,并且可以使用 .catch方法。 这个承诺可以转发给其他客户。
添加回答
举报
0/150
提交
取消
