Q:

$http.post() angularjs response function not executing in right order

From my angular controller I'm making a function call to do $http.post() request. 
$scope.formSuccess = false;

$scope.submit = function(serviceName) {
   submitRequest(serviceName);
   if($scope.formSuccess) {
      // do something 
    }
};

var submitRequest = function(serviceName) {
   $http.post(serviceName, data, { headers: { 'Content-type':   'application/json' }  
  }).then(successFunction, errorFunction);
};

var successFunction = function(response) {
  $scope.formSuccess =true;
};

the code below the submitRequest() is executing first than the successFunction() so  the code inside if block is never executing. how can i do that. I don't want to move if block to successFunction.

A:

The problem is this line if($scope.formSuccess) { is executed before http request is done, hence the statement inside the if is never executed. 
The cleanest solution would be to introduce functions to be execute on $http.post success and failure

$scope.formSuccess = false;

$scope.submit = function(serviceName) {
   submitRequest(serviceName)
    .then(onPostSuccess)
    .catch(onPostFail);
};

var submitRequest = function(serviceName) {
   return $http.post(serviceName, data, { headers: { 'Content-type':   'application/json' }  
   });
};

var onPostSuccess = function(response) {
  $scope.formSuccess = true;
  //do your stuff here
  
};

var onPostFail = function(response){
  $scope.formSuccess = false;
  //show form failed
}

