0

I require the user details for multiple areas. I tried to return the details using a generic function. But i am getting the result as undefined. i understand that, I require to use the $differed to get the reuslt. But I don't have any idea about my current scenario.

anyone help me here please?

here is my function:

$scope.currentUserInfo = function () {

        var userDetails;

        server.getProfile.get().$promise.then(function ( response ) {

            if( response.Message.toUpperCase().indexOf('SUCCESS') != -1) {

                return  userDetails = response;

            }

            return "Not able to get the user details this time"

        })

        return userDetails;

    }

$scope.currentUser =  $scope.currentUserInfo();
console.log( $scope.currentUser ) //undefined.



var function1 = function () {

    $scope.currentUserInfo(); //once user details available do further

     $scope.age = $scope.currentUser.age;

}

var function2 = function () {

    $scope.currentUserInfo(); //once user details available do further

    $scope.name = $scope.currentUser.name;

}
3gwebtrain
  • 13,401
  • 21
  • 93
  • 195
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Grundy Jan 06 '16 at 06:42

1 Answers1

1

server.getProfile.get() is an asynchronous call. The return userDetails; line in $scope.currentUserInfo function will get executed even if the server.getProfile.get() call is not yet finish. Try this:

$scope.currentUserInfo = function () {

    server.getProfile.get().$promise.then(function ( response ) {

        if( response.Message.toUpperCase().indexOf('SUCCESS') != -1) {

            $scope.currentUser = response;

        }

        $scope.message =  "Not able to get the user details this time";


    })

}

$scope.currentUser will be populated after the ajax call is finish. I assume that you are using $scope.currentUser in your html bindings so when the value changes it will automatically reflect in your view

3gwebtrain
  • 13,401
  • 21
  • 93
  • 195
PrinceG
  • 882
  • 6
  • 17
  • I agree. But Up to I receive the value from the `$scope.currentUser` I would like to `pause` other functions - how to do? – 3gwebtrain Jan 06 '16 at 06:24
  • What do you mean by pause other functions? – PrinceG Jan 06 '16 at 06:28
  • 1
    how or where do you use `function1` and `function2`? if for instance you want to do something when `$scope.currentUser` changes, you may want to `watch` `$scope.currentUser` – PrinceG Jan 06 '16 at 06:40