代码之家  ›  专栏  ›  技术社区  ›  Noor A Shuvo

在angularjs中一个接一个地调用异步方法

  •  0
  • Noor A Shuvo  · 技术社区  · 7 年前

    我有一个 $watch 附加到 appId 变量。所以,当appid被更改时,它调用 init 功能

    $scope.$watch('appId', function() {                
        if ($scope.appId != '') {
            console.log('Inside appId watch');
            $scope.init();
        }
    });
    

    init() 调用两个服务方法

    $scope.init = function() {
    
        if ($scope.appId === undefined || $scope.appId == '') return false;
    
        $scope.getPrincipals($scope.loadPrincipals);
        $scope.getSignaturesByAppId($scope.loadSignatures);     
    
    };
    

    方法是

    $scope.getSignaturesByAppId = function (callback) {
        ApplicationDataSource.getSignaturesByAppId($scope.appId, function (result) {
            callback(result);
            $scope.$apply();
        });
    };
    
    
    $scope.loadSignatures = function (result) {
        var signatureResultSet = angular.fromJson(result[0]);
        $scope.appSignatures = signatureResultSet;
    
        if($scope.appSignatures.length===0){
            $scope.setDefaultValue();
        }
        else{
            $scope.setValueFromObject();
        }
    
    };
    
    $scope.getPrincipals = function (callback) {
        ApplicationDataSource.getApplicationPrincipalList($scope.appId, function (result) {
            callback(result);
            $scope.$apply();
        });
    };
    
    $scope.loadPrincipals = function (result) {
        var guarantorResultSet = angular.fromJson(result[0]);
        $scope.principals = guarantorResultSet;
    };
    

    问题就发生在这里。在 loadSignatures() ,我调用了一个方法 setDefaultValue() 需要从 loadPrincipals . 所以,什么时候, loadSignatures 打电话, principal 数据未更新。

    如何调用 $scope.getPrincipals($scope.loadPrincipals) 之后 $scope.getSignaturesByAppId($scope.loadSignatures) 完成检索数据。

    2 回复  |  直到 7 年前
        1
  •  3
  •   zuckerburg    7 年前

    你可以使用承诺,下面是一个例子:

    var promise = callThatRunsInBackground();
    
    promise.then(
      function(answer) {
        // do something
      },
      function(error) {
        // report something
      },
      function(progress) {
       // report progress
      });
    

    所以在您的代码中,它可能看起来像(我将把它留给您来修复,因为我不会编译或检查语法错误):

    var getPrincipals = $scope.getPrincipals($scope.loadPrincipals);
    
    getPrincipals.then(
           function(datapayload) {  
                //do something with datapayload perhaps
                $scope.getSignaturesByAppId($scope.loadSignatures); 
         });
    

    这将使它在运行getSignaturesByAppID之前等待getPrinciples完成

        2
  •  0
  •   Noor A Shuvo    7 年前

    解决我问题的办法是,我打电话给 $scope.getSignaturesByAppId($scope.loadSignatures); 在里面 loadPrincipals 回调函数,不在 init()

    $scope.loadPrincipals = function (result) {
           var guarantorResultSet = angular.fromJson(result[0]);
           $scope.principals = guarantorResultSet;
    
           $scope.getSignaturesByAppId($scope.loadSignatures); 
    };