在拒绝与AngularJS多个参数的承诺(如$ HTTP) [英] Rejecting promises with multiple arguments (like $http) in AngularJS

查看:109
本文介绍了在拒绝与AngularJS多个参数的承诺(如$ HTTP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回调 $ HTTP 承诺有多个参数:身体,状态,头,配置

Callbacks for $http promises have multiple arguments: body, status, headers, config.

我想手动创建类似承诺,但不知道如何做到这一点。我想要做的是多还是少:

I'd like to create similar promise by hand but don't know how to do this. What I'd like to do is more or less:

myservice.action().then(function(status, message, config) {
    // ...
});

我知道我可以通过与键的对象回调,但希望有类似的公约为 $ HTTP 。我看角来源,但要么不完全理解它,还是不能做正确的。

I know I could pass object with keys to callback but would like to have similar convention as in $http. I look at the angular sources, but either don't understand it fully or just can't do that right.

你知道如何创建能够通过多个参数回调承诺/ errbacks?

Do you know how to create promises that are able to pass multiple arguments to callback/errbacks?

推荐答案

由于在意见建议,看看在 $ Q AngularJS的实施。该文档是臭名昭著的是......嗯有时候很难理解。

As suggested in the comments, have a look at the $q implementation of AngularJS. The docs are notorious for being... well hard to understand sometimes.

但无论如何,让我们尝试简短的例子。我这样做是CoffeeScript的,因为我preFER它,但你应该能够在 coffeescript.org 来编译示例如果你想。

But anyway, let's try a short example. I do this in CoffeeScript, because I prefer it, but you should be able to compile the example at coffeescript.org if you want to.

让我们实现一个服务:

app = angular.module 'my.custom.services', ['your.other.modules']

app.factory 'Service', ['$http' , '$q', (http, q) ->

  # this is your deferred result
  deferred = q.defer()

  get: ->
    deferred.promise
]

这一个是容易的。这只是一个服务,它会利用 $ Q $ HTTP ,因为一)我们要一些这基于甜蜜承诺-的东西,我们在谈论和b)'$ HTTP是一个很好的例子本身的东西,可以异步调用和查询的结果不可的时候了。

This one is easy. It's just a service, which will make use of $q and $http, because a) we want some of this sweet promise-based stuff we're talking about and b) '$http' is a nice example in itself for something that can call asynchronous and which's result is not available right away.

在这里有趣的是,在这里返回的对象的 GET 部分。注意,该服务将作为工厂实施,而不是作为一个服务。对于差异,请参见这里。我通常把它作为一个神奇的版本为服务,在这里我只是公开服务的API之前,有我自己的逻辑一些额外的空间(它的真正含义了另一个故事不同的东西,但多数民众赞成。

The interesting part here is the get part of the object that is returned here. Take note, that the service is implemented as a factory, not as a service. For the differences, see here. I usually think of it, as a "fancy" version for a service, where I just have some extra space for my own logic before exposing an API of the service (it really means something different, but thats for another story.

总之, GET 将调用时返回延期对象的。在是一个对象,它公开了一个然后方法。当使用这个服务,你可能会注入像:

Anyway, get will return the promise of the deferred object when called. The promise is an object, which exposes a then method. When using this service, you'll probably inject it like:

app = angular.module 'my.custom.application', ['my.custom.services']

app.controller 'AppController', ['Service', (service)->

  service.get() # then what?

]

正如我所说, GET 将只返回一个承诺。公司承诺,在现实生活中,必须要解决的地方。因此,让我们做的服务 - 我们的承诺将得到解决,当我们与我们所承诺的任务完成了。这可以像调用通过AJAX URL或一个大的计算(有人知道第117 Fibonacci数是什么?)。

As I mentioned, get will just return a promise. Promises, as in real life, have to be resolved somewhere. So let's do that in the service - our promise will get resolved, whenever we're finished with the task we promised. This can be something like calling a URL via AJAX or a big calculation (anyone knows what the 117th Fibonacci number is?).

在我们的例子中,我们使用HTTP调用,像我们现在不这样做,是否不和,即使它会回到我们:

For our example, we use an http-call, as we do not now, whether or not and even when it will return to us:

app.factory 'Service', ['$http' , '$q', (http, q) ->

  # this is your deferred result
  deferred = q.defer()

  # this is where http is used, this is started immediately, but takes a while
  http.get('some-resource.json').then (response) ->
    # now 'response' is the whole successful response, it has a data object with the payload
    if !someCondition
      deferred.resolve response.data #we have what we wanted
    else
      deferred.reject {error: "Failed", additional: "foo", number: 2} #we ran into some error

  get: ->
    deferred.promise
]

根据 someCondition 我们可以让请求故意失败,如果我们想。如果您想尝试一下你自己,你也可以使用暂停像文档。

Based on someCondition we can let the request fail on purpose if we want. If you want to try it your self, you can also use a timeout like in the docs.

现在情况如何?好了,我们还是有一个控制器周围:

What happens now? Well, we still have that controller around:

app.controller 'AppController', ['Service', (service)->

  service.get().then(successCallback, errCallback)

]

正如我所解释的,公开了一个然后方法与签名则(成功,错误),其中成功错误是采取一切我们解析为函数参数,例如:

As I explained, the promise exposes a then method with the signature then(success, error), wherein success and error are functions that take whatever we resolved as arguments, e.g.:

app.controller 'AppController', ['Service', (service)->
  successCallback = (data) ->
    # we can work with the data from the earlier resolve here
    scope.data = data

  errCallback = (err) ->
    # the error object, we got from the rejection
    console.log err.error # => "Failed"

  service.get().then(successCallback, errCallback)

]

如果你想多个值传递给回调,我建议你解决/拒绝承诺时传递的对象。你也可以做一个名为回调的承诺,像角是否在它的 $ HTTP 实施

if you want multiple values to be passed to the callbacks, I'd suggest you pass an object when resolving/rejecting the promise. You can also do named callbacks for the promise, like angular does in it's $http implementation:

app.factory 'Service', ['$http' , '$q', (http, q) ->

  # this is your deferred result
  deferred = q.defer()

  # [...]

  get: ->
    promise = deferred.promise

    promise.success = (fn) ->
      promise.then (data) ->
       fn(data.payload, data.status, {additional: 42})
      return promise

    promise.error = (fn) ->
      promise.then null, (err) ->
        fn(err)
      return promise

    return promise 
]

您实质上扩展由一个方法成功,这需要一个单一的方法作为回调,等待承诺解决,然后使用回调归还的承诺。如果你想(为线索,见角的实施

You essentially extend the promise given back by a method success, which takes a single method as a callback, waits for the promise to be resolved and then uses the callback. You can do the same for an any other method if you want to (for hints, see the angular implementation)

在你的控制器,你可以使用它是这样的:

In your controller, you can then use it like this:

service.get().success (arg1, arg2, arg3) ->
  # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
  # => err

这是基础,如果你愿意,你可以尝试,我建议你尝试以下方法:

This is the basics, you can experiment if you want, I suggest you try the following:


  • 在多个延期承诺服务承诺多

  • 尝试推迟的结果,像长计算的另一种方法

和,作为奖励:


  • 尝试隔离成功/错误回调到服务的命名方法

本示例使用许诺角,你当然可以用另一个实施 $ Q 的实施,像的这个,这是依据 $ q

This example uses the $q implementation in Angular, you can of course use another implementation for promises, like this one, which is the basis for $q.

这篇关于在拒绝与AngularJS多个参数的承诺(如$ HTTP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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