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

3

9

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?

Yukoyukon answered 15/2, 2016 at 17:39 Comment(0)
S
6

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

Septillion answered 15/2, 2016 at 20:15 Comment(0)
L
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

Lamia answered 15/2, 2016 at 17:45 Comment(0)
V
0

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.

Viehmann answered 15/2, 2016 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.