在异步请求angularjs简单。然后或$ Q服务 [英] angularjs simple .then or $q service in async requests

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

问题描述

我不知道什么是 $ Q 服务AngularJS之间到底有什么不同,只是使用。然后()异步请求后。

简单的例子。然后()

 函数InboxService($ HTTP){
  this.getEmails =功能getEmails(){
    返回$ http.get('/电子邮件');
  };
}

和使用服务(只需code部分)时:

  InboxService.getEmails()
。然后(功能(响应){
  //使用响应
});

有什么用 $ Q 服务的区别与决心,并拒绝


解决方案

  

有什么用$ Q服务的差异有决心和拒绝?


我以为你是问关于 VAR推迟= $ q.defer()随后 deferred.resolve() deferred.reject()?在这种情况下,答案是,你不需要它,因为你已经有了由 $ HTTP 服务返回的承诺对象。事实上,手动建设有 $ Q 不建议将另一个新的承诺,并认为是的反模式

在那里你与那些没有裹成承诺异步函数(超时,Ajax的请求)工作的情况,那么这时候你可能想使用情况 $ Q 以创建并返回承诺。但再次,你的情况,你不需要它为 $ HTTP 服务承诺构造为你和一个更根本就是多余的。

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 ?

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆