首页 > 解决方案 > Angularjs承诺等待结果

问题描述

在我的 angularjs 应用程序中,单击按钮时有以下代码:

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
        $scope.userName = data;    
    });
  }

  //some processing code here then another promise  

 myService.save($scope.userName,otherparams).then(function (res) {
       //route to page
    }, function (err) {
 });

这里的问题是,如果 $scope.isChecked 为假,它会进入 promise 内部,并且由于需要时间来解决它会出现并进入下一行代码。因为这个 $scope.userName 没有更新,而是使用旧值而不是返回的更新值。

处理这个问题的最佳方法是什么?

标签: javascriptangularjs

解决方案


如果 myService.save 需要等待 $scope.getExistingName 承诺,只需在“then”语句中计算该操作。

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
         $scope.userName = data;    
         myService.save($scope.userName,otherparams).then(function (res) {
             //route to page
         }, function (err) {
         });
    });
  }

  //some processing code here then another promise  


推荐阅读