问题
Take a look at this method returned in a factory:
fetchEmployeeList: function() {
var q = $q.defer();
$http.get('/Employee/')
.success(q.resolve)
.error(ajaxErrorHandler.handleError);
return q.promise;
}
The author of this code says that this is the model we should use for returning data from HTTP endpoints. Basically, any time we need data from a service, we should use this pattern. The author is under the impression that this is preferred over returning $http.get()'s return value instead.
I don't understand the point of this code, though. I thought $http.get() does return a promise.
Can someone explain what this example snippet is doing or what they think the author might be trying to do?
回答1:
That's the deferred anti-pattern, which practically warps a promise when not needed.
in your case returning a q.promise seems like an abuse since the HTTP object can return a promise itself.
I'd refactor the code to the following:
fetchEmployeeList: function() {
return $http.get('/Employee/');
}
you can take a look to this blog post for more reference as well,
don't be afraid to open a discussion with whoever is suggesting that approach.
来源:https://stackoverflow.com/questions/26919251/pattern-for-returning-data-from-angular-ajax-calls