angularjs - Angular HttpPromise : difference between `success` /`error` methods and `then` 's arguments

标签 angularjs promise

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

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对象在一种情况下被解构这一事实之外,我不明白两者之间的区别

  • 作为 promise.then 的参数传递的成功/错误回调
  • 作为 Promise 的 promise.success/promise.error 方法参数传递的回调

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

最佳答案

这里已经有一些很好的答案。但值得深入了解所提供的并行性的差异:

  • success() 返回原始 Promise
  • then() 返回一个新的 Promise

不同之处在于 then() 驱动顺序操作,因为每次调用都会返回一个新的 Promise。

$http.get(/*...*/).
  then(function seqFunc1(response){/*...*/}).
  then(function seqFunc2(response){/*...*/})
  1. $http.get()
  2. seqFunc1()
  3. seqFunc2()

success() 驱动并行操作,因为处理程序链接在同一个 Promise 上。

$http(/*...*/).
  success(function parFunc1(data){/*...*/}).
  success(function parFunc2(data){/*...*/})
  1. $http.get()
  2. parFunc1()parFunc2() 并行

关于angularjs - Angular HttpPromise : difference between `success` /`error` methods and `then` 's arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385278/

相关文章:

node.js - 在 promisifyAll 创建的 then 链中使用 cancel()

javascript - 在 jQuery AJAX 调用中是否有任何类似于 'finally' 的东西?

javascript - 如何链接 HTML5 fetch()?

javascript - JSON 文件内容未在 HTML 中加载

AngularJS Protractor : Step-by-step progress logs

javascript - 使用 AngularJS 发送 GET 请求时无法从 WebStorm IDE 执行 'open' 无效 URL

javascript - 如何包装 Javascript 函数以便捕获所有错误,包括 Promise 拒绝

javascript - 试图让 Angularjs 显示 promise 时出现无限循环

javascript - 试图嵌入一个选择元素

javascript - JQuery toggleClass() 打开然后关闭(或删除)