Pattern for returning data from Angular AJAX calls

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 03:15:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!