Angular HttpPromise:`success`/`error` 方法和`then` 的参数之间的区别 [英] Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

查看:20
本文介绍了Angular HttpPromise:`success`/`error` 方法和`then` 的参数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 AngularJS doc,对 $http 的调用返回以下内容:

According to AngularJS doc, calls to $http return the following:

使用标准的then 方法和两个特定于http 的方法返回promise 对象:successerror.then 方法接受两个参数,一个 success 和一个 error 回调,它们将被一个响应对象调用.successerror 方法采用单个参数 - 分别在请求成功或失败时调用的函数.传递给这些函数的参数是传递给 then 方法的响应对象的解构表示.

Returns a promise object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method.

除了 response 对象在一种情况下被解构这一事实之外,我不明白

Aside from the fact that the response object is destructured in one case, I don't get the difference between

  • 作为promise.then的参数传递的成功/错误回调
  • 作为 promise.success/promise.error 方法的参数传递的回调
  • the success/error callbacks passed to be passed as arguments of promise.then
  • the callbacks passed as arguments for the promise.success/promise.error methods of the promise

有吗?这两种不同的方式来传递看似相同的回调有什么意义?

Is there any? What's the point of these two different ways to pass seemingly identical callbacks?

推荐答案

NB 这个答案实际上是不正确的;正如下面的评论所指出的,success() 确实返回了最初的承诺.我不会改变;并将其留给 OP 进行编辑.

NB This answer is factually incorrect; as pointed out by a comment below, success() does return the original promise. I'll not change; and leave it to OP to edit.

两者之间的主要区别在于 .then() 调用返回一个 promise(通过回调返回的值解析)而 .success() 则更多注册回调的传统方式并且不返回承诺.

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

基于 Promise 的回调 (.then()) 使链接 Promise 变得容易(执行一个调用,解释结果,然后 then 执行另一个调用,解释结果,执行另一个电话等).

Promise-based callbacks (.then()) make it easy to chain promises (do a call, interpret results and then do another call, interpret results, do yet another call etc.).

.success() 方法是一种简化的、方便的方法,当您不需要链接调用或使用 promise API 时(例如,在路由中).

The .success() method is a streamlined, convenience method when you don't need to chain call nor work with the promise API (for example, in routing).

简而言之:

  • .then() - Promise API 的全部功能,但稍微冗长一些
  • .success() - 不返回承诺,但提供更方便的语法
  • .then() - full power of the promise API but slightly more verbose
  • .success() - doesn't return a promise but offeres slightly more convienient syntax

这篇关于Angular HttpPromise:`success`/`error` 方法和`then` 的参数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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