为什么回应来自承诺`.then`方法反模式 [英] Why are Callbacks from Promise `.then` Methods an Anti-Pattern
问题描述
我在StackOverflow上看到了人们建议为AngularJS服务提供回调函数的答案。
I have seen answers on StackOverflow where people suggest furnishing a callback function to an AngularJS service.
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
服务返回promises并且 .then
方法执行回调函数感觉就像是一个不健康的控制反转。
This seems to me to be an Anti-Pattern. The $http
service returns promises and having .then
methods execute callback functions feels like an unhealthy inversion of control.
一个重新分解代码怎么样?如何解释为什么原来的方式不是一个好主意?
How does one re-factor code like this and how does one explain why the original way was not a good idea?
推荐答案
可以按如下方式重新计算代码:
The code can be re-factored as follows:
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
承诺的方法,同样的功能实现了以下好处:
By having the service return a promise, and using the .then
method of the promise, the same functionality is achieved with the following benefits:
-
承诺可以保存并用于链接。
可以保存并使用承诺,以避免重复相同的 $ http
致电。
The promise can be saved and used to avoid repeating the same $http
call.
保留错误信息,可以使用 .catch $ c $检索c>方法。
Error information is retained and can be retrieved with the .catch
method.
承诺可以转发给其他客户。
The promise can be forwarded to other clients.
这篇关于为什么回应来自承诺`.then`方法反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!