简体   繁体   中英

AngularJs how to make sure code executed synchronously

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

        });
    };  

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();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM