Sachin Sharma
Sachin Sharma

Reputation: 1496

function calls in angular JS controller are executed in random order

app.controller('attributeFormCtrl', ['$scope', '$route', '$log', '$modalInstance', 'attributeService', function($scope, $route, $log, $modalInstance, attributeService) {

    $scope.someMethod = function(){
        attributeService.getAllAttributeTypes().then(function(response){
            $scope.attributeTypes=response.data;
            }, function(error){
                // some error occurred
        });

        attributeService.getAttributeById($scope.attributeId).then(function(response){
            $scope.attribute=response.data;
        },function(error) {
            // error occurred.
        });
    };

    $scope.cancel = function() {
          $modalInstance.close();
    };

    $scope.someMethod();
}]);

Upvotes: 2

Views: 1929

Answers (2)

Jacques Cornat
Jacques Cornat

Reputation: 1652

There is no random in JavaScript.

In your case, getAllAttributeTypes function is called first, then getAttributeById, BUT, the .then() means there is a callback and function getAllAttributeTypes will take sometimes more time than the second one, that's why $scope.attributeTypes=response.data; is called after $scope.attribute=response.data; in some cases.

This is not an Angular specificity, but a JavaScript one.

Upvotes: 1

jValdron
jValdron

Reputation: 3418

You're using asynchronous methods that returns a promise. Depending on a ton of factors, one might finish before the other, as you've found out.

If you need one to execute before the other, you can call one before the other, and then call the other within the callback function, as such:

$scope.someMethod = function(){
    attributeService.getAllAttributeTypes().then(function(response){
        $scope.attributeTypes=response.data;

        attributeService.getAttributeById($scope.attributeId).then(function(response){
            $scope.attribute=response.data;
        },function(error) {
            // error occurred.
        });
    }, function(error){
        // some error occurred
    });
};

That way you'll always be sure of which one finishes first.

Upvotes: 2

Related Questions