AngularJS then() behaves differently than success()-error() [duplicate]

本小妞迷上赌 提交于 2019-12-06 21:37:22

问题


As the success() and error() functions are deprecated in AngularJS, I am updating my codes, replacing them with then(). Now according to my understanding, these two pieces of codes should behave identically:

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

And

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

But in some cases I am getting different behavior. Can you please explain to me why would that happen, and more importantly, what would be the way to guarantee the identical behavior using then() functions?


回答1:


The .success and .error methods ignore return values.
Consequently they are not suitable for chaining.

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
});

On the otherhand, the .then and .catch methods return a derived promise suitable for chaining from returned (or throw) values or from a new promise.

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);
});

Response Object vs Four Arguments

Also notice that the $http service provides four arguments (data, status, headers, config) when it invokes the function provided to the .success and .error methods.

The $q service only provides one argument (response) to the functions provided to the .then or .catch methods. In the case of promises created by the $http service the response object has these properties:1

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

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


Update

The .success and .error methods have been deprecated and removed from AngularJS V1.6.

For more information, see

  • Why are angular $http success/error methods deprecated? Removed from v1.6?.



回答2:


One important difference is that you should probably use .then().catch() instead of .then(function(), function()). [1] The two-argument then (where the second function is the error handler) does not capture errors in the first function, as I understand it. IOW: $http.get().then(a, b) will not call b() if a() throws an error, where as $http.get().then(a).catch(b) will.

What other sorts of different behaviors are you getting?

1: standardized Promise API - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise




回答3:


The success function and the promise callback indeed receive different objects. As described in the docs, the promise callback receives a response object containing status, headers, data etc. The success function returns just the data field (the response body) of that object.



来源:https://stackoverflow.com/questions/35415659/angularjs-then-behaves-differently-than-success-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!