davidx1
davidx1

Reputation: 3673

What does it mean to pass 2 functions into '.then()'? (Angular.js)

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

Upvotes: 0

Views: 83

Answers (2)

Syed Ekram Uddin
Syed Ekram Uddin

Reputation: 3091

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

Upvotes: 1

user229044
user229044

Reputation: 239291

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.

Upvotes: 3

Related Questions