本文介绍了异步请求中的 angularjs 简单 .then 或 $q 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道 AngularJS $q 服务和在异步请求后简单地使用 .then() 之间的确切区别是什么.

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

带有 .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
});

$q服务解决和拒绝有什么区别?

推荐答案

我假设您在询问 var deferred = $q.defer() 与后续 deferred.resolve()deferred.reject()?在这种情况下,答案是您不需要它,因为您已经拥有 $http 服务返回的承诺对象.事实上,不推荐使用 $q 手动构建另一个新的 Promise 并且被认为是 反模式.

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.

如果您使用尚未包装到 promise 中的异步函数(超时、ajax 请求),那么您可能希望使用 $q 来创建和返回承诺.但是再一次,在您的情况下,您不需要它,因为 $http 服务为您构造了承诺,而另外一个只是多余的.

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.

这篇关于异步请求中的 angularjs 简单 .then 或 $q 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:05