angularjs simple .then or $q service in async requests

送分小仙女□ 提交于 2019-12-20 04:24:28

问题


I don't know what is the exactly difference between AngularJS $q service and simply using .then() after async request.

Simple example with .then() :

function InboxService($http) {
  this.getEmails = function getEmails() {
    return $http.get('/emails');
  };
}

And when using the service (just part of code):

InboxService.getEmails()
.then(function (response) {
  // use response
});

What is the difference with $q service with resolve and reject ?


回答1:


What is the difference with $q service with resolve and reject ?

I assume you are asking about the usage of var deferred = $q.defer() with subsequent deferred.resolve() or deferred.reject()? In this case, the answer is that you don't need it since you already have a promise object returned by $http service. In fact, manually constructing another new promise with $q is not recommended and considered an anti-pattern.

In cases where you work with asynchronous functions (timeouts, ajax-requests) that are not already wrapped into promise, then this is a case when you might want to use $q to create and return promise. But once again, in your case you don't need it as $http service constructs promise for you and one more is simply redundant.




回答2:


The $q is superfluous and in most cases is not needed. http://www.codelord.net/2015/09/24/$q-dot-defer-youre-doing-it-wrong/



来源:https://stackoverflow.com/questions/36631601/angularjs-simple-then-or-q-service-in-async-requests

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