Jakub Kuchar
Jakub Kuchar

Reputation: 1665

javascript, object, passing function as arguments with arguments- angular, jquery concept basic misunderstanding

I am trying to understand what i am really doing, since i feel i am lack of something. Could you please point me somewhere or confirm my mis/understanding?

request.then(function(response) {
        updateCurrentUser(response.data.data);
        currentUser.isAuthenticated();
      });

Is basically this?

request = {
    then : function (foo){
        foo("first")
    } }

request.then(function (response) { console.log(response) ; });

If you see full code here#35 and here#63

directive:

    AuthenticationService.login($scope.user.email, $scope.user.password).then(function(loggedIn) {
      if ( !loggedIn ) {
        $scope.authError = "Login failed.  Please check your credentials and try again.";
      }
    });

AuthenticationService as factory:

login: function(email, password) {
  var request = $http.post('http://', {email: email, password: password});
  return request.then(function(response) {
    updateCurrentUser(response.data.data);
    return currentUser.isAuthenticated();
  });

},

The thing i don't understand is how come that the value of loggedIn variable is equal to the value what statement return currentUser.isAuthenticated(); returning AND NOT equal to the then(function(response) of original as i am returning promise from AuthenticationService. And how this could be accomplished regarding to the examples above?

Thank you.

Upvotes: 2

Views: 286

Answers (1)

Stan
Stan

Reputation: 8768

I think the problem with conception arises from the fact that you overlooked the return statement. What AuthenticationService.login does is actually a closure with predefined request, so you can imagine that login is replaced with its return value request.then(function(response) {.... Then you can simply deduce that entire code row is:

AuthenticationService.login($scope.user.email, $scope.user.password).then(
function(response)
{
    updateCurrentUser(response.data.data);
    return currentUser.isAuthenticated();
}).then(
function(loggedIn)
{
  ...

This way you may see that result from response should occur as input for the next step with login check.

Upvotes: 2

Related Questions