angular JS 控制器中的函数调用以随机顺序执行

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

您正在使用 returns 和 promise 的异步方法。正如您所发现的,取决于大量因素,一个可能先于另一个完成。

如果你需要一个先于另一个执行,你可以先调用一个,然后在回调函数中调用另一个,这样:

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

这样您就可以始终确定哪一个先完成。

JavaScript中没有随机数。

在您的情况下,首先调用 getAllAttributeTypes 函数,然后调用 getAttributeById,但是,.then() 意味着有一个回调函数 getAllAttributeTypes 有时会花费更多时间比第二个,这就是为什么在某些情况下 $scope.attribute=response.data; 之后调用 $scope.attributeTypes=response.data; 的原因。

这不是 Angular 特异性,而是 JavaScript 特异性。