1

I have a button on a page which calls the process function within a controller but before I post the details I need to get the user details and userGroup details, and finally post the user details.

But when I debug this I can see my populateUserGroups function is called but without getting the details the updateUser function is called hence the posted data does not have the userGroup data.

It seems the populateUserGroups function is called asynchronously, how can I make sure when users click the Process button, first getData is called, then populateUserGroups is called and $scope.user.userGroups is populated with the returned data and finally updateUser is called?

    $scope.process = function () {
        myservice.getData($scope.userId).success(function (data) {

                $scope.user = data.value;
                $scope.user.userGroups = {};

                $scope.populateUserGroups();
                $scope.updateUser();

        });
    };

    $scope.populateUserGroups = function () {
        myservice.getUserGroups($scope.userId).success(function (groupData) {
            $scope.user.userGroups = groupData;
        });
    };

    $scope.updateUser = function() {
        myservice.updateUser($scope.user).success(function () {

            // do stuff

        });
    };  
3
  • Call the second function in the first function's callback? Commented Jun 29, 2015 at 12:19
  • 1
    Use promises ideally with services that return promises. See $q Commented Jun 29, 2015 at 12:20
  • use async,npmjs.com/package/async Commented Jun 29, 2015 at 12:21

1 Answer 1

1

use $q.all

$q.all([
  myservice.getData($scope.userId),
  myservice.getUserGroups($scope.userId)
]).then(function(resps){
  $scope.user = resps[0].value;
  $scope.user.userGroups = resps[1].data;

  $scope.populateUserGroups();
  $scope.updateUser();
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.