0

I'm reading some tutorial on angular.js and came across this expression:

.then(handleRequest, handleRequest)

I was wondering what does it mean to pass 2 of the same functions into .then()?

Here's more context:

function MainCtrl(user, auth) {
  var self = this;

  function handleRequest(res) {
    var token = res.data ? res.data.token : null;
    if(token) { console.log('JWT:', token); }
    self.message = res.data.message;
  }

  self.login = function() {
    user.login(self.username, self.password)
      .then(handleRequest, handleRequest)
  }

  ...

}

angular.module('app', [])
.controller('Main', MainCtrl)
....
})();

And the original tutorial can be found here: https://thinkster.io/angularjs-jwt-auth

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
davidx1
  • 3,525
  • 9
  • 38
  • 65
  • 1
    Have a look [over here](http://stackoverflow.com/a/24663315/1048572). In this case, it looks like an attempt to get the behavior of `.finally(handleRequest)` which should actually have been used. – Bergi Apr 22 '16 at 00:22
  • possible duplicate of [Confuse about error and reject in Promise](http://stackoverflow.com/q/35282803/1048572) – Bergi Apr 22 '16 at 00:33

2 Answers2

3

The then method is defined as:

promise.then(onFulfilled, onRejected)

The first argument is invoked when the promise is fulfilled.

The second argument is invoked when the promise is rejected.

Passing the same callback function as both arguments means the author intended the same function to handle both the fulfillment or rejection of the promise.

Read the complete spec for more details.

user229044
  • 232,980
  • 40
  • 330
  • 338
1

first one for successCallback and the second one for errorCallback. So

// Simple GET request example:
$http({
 method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Promises a bit complex pattern to understand. The best resource to me is

Promises in AngularJS, Explained as a Cartoon

Syed Ekram Uddin
  • 2,907
  • 2
  • 29
  • 33