AngularJS then() 的行为不同于 success()-error()

AngularJS then() behaves differently than success()-error()

由于 success()error() 函数在 AngularJS 中已弃用,我正在更新我的代码,将它们替换为 then()。现在根据我的理解,这两段代码的行为应该相同:

$http
   .get(/* some params */)
   .success(function() {
      // success cases here
   })
   .error(function() {
      // error cases here
   });

$http
   .get(/* some params */)
   .then(function() {
      // success cases here
   }, function() {
      // error cases here
   });

但在某些情况下,我会遇到不同的行为。您能否向我解释为什么会发生这种情况,更重要的是,使用 then() 函数保证相同行为的方法是什么?

一个重要的区别是您可能应该使用 .then().catch() 而不是 .then(function(), function())。 [1] 据我所知,双参数 then(第二个函数是错误处理程序)不会捕获第一个函数中的错误。 IOW:如果 a() 抛出错误,$http.get().then(a, b) 将不会调用 b(),而 $http.get().then(a).catch(b) 会。

您还有哪些其他类型的不同行为?

1:标准化的 Promise API - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

成功函数和 promise 回调确实接收到不同的 object。如 docs 中所述,promise 回调接收到包含状态、headers、数据等的响应 object。成功函数 returns 只是数据字段(响应 [= object 的 13=])。

.success.error 方法 忽略 return 值
因此它们不适合链接

var httpPromise = $http
       .get(/* some params */)
       .success(function onSuccess(data, status, headers, config) {
          var modifiedData = doModify(data);
          //return value ignored
          return modifiedData;
       })
       .error(function onError(data, status, headers, config) {
          // error cases here
       });

httpPromise.then(function onFullfilled(response) {
    //chained data lost
    //instead there is a response object
    console.log(response.data); //original data
    console.log(response.status); //original status
});

另一方面,.then.catch方法return一个派生的promise适合链接 来自 returned(或抛出)值或来自新的承诺。

var derivedPromise = $http
       .get(/* some params */)
       .then(function onFulfilled(response) {
          console.log(response.data); //original data
          console.log(response.status); //original status

          var modifiedData = doModify(response.data);
          //return a value for chaining
          return modifiedData;
       })
       .catch(function onRejected(response) {
          // error cases here
       });

derivedPromise.then(function onFullfilled(modifiedData) {
    //data from chaining
    console.log(modifiedData);
});

响应Object vs 四个参数

另请注意,$http 服务在调用提供给 .success 和 [=13] 的函数时提供 四个参数 (data, status, headers, config) =] 方法。

$q 服务仅向 .then.catch 方法提供的函数提供 一个参数 (响应)。对于由 $http 服务创建的承诺,响应 object 具有以下属性:1

  • data – {string|Object} – 使用转换函数转换的响应 body。
  • status – {number} – 响应的 HTTP 状态代码。
  • headers – {function([headerName])} – Header getter 函数。
  • config – {Object} – 用于生成请求的配置 object。
  • statusText – {string} – 响应的 HTTP 状态文本。

Chaining promises

Because calling the then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.2


更新

.success.error 方法已被弃用并从 AngularJS V1.6 中删除。

有关详细信息,请参阅