首页 > 解决方案 > 在 Angular js 应用程序中,如何让其他代码等到某些代码完成?

问题描述

在 Angular js 应用程序中,如果必须向数据库发送请求,并且在响应到来之前不应该执行其他操作,现在我无法做到这一点

function checkStep() {
  if (currenctStep == 1 && checkBalance()) { // request database to check balance
    alert('balance is not enough');  
  } else if (currentStep == 2) {
    goToNextStep();
  } else if (currentStep == 3) {
    validateAll();
  }
 // ... some actions should wait until above codes are executed, 
 // here some codes that do some actions and should change current step after 
 // checkBalance() respose comes
} 

我该怎么做才能让所有其他代码等到响应到来checkBalance()

标签: angularjs

解决方案


checkBalance是异步调用,ti 应该返回一个承诺。

就像是:

function checkStep() {
  if (currenctStep == 1) { // request database to check balance

   checkBalance().then(function (response) {
       // parse response data
       if (currentStep == 2) {
         goToNextStep();
        } else if (currentStep == 3) {
        validateAll();
      }
   }, function (error) {
       // failed to call DB                        
   });
  } 
 // ... some actions
} 

哪里checkBalance可以:

function checkBalance() {
     // some call DB here
    return $http({method: 'GET', url:URL}).then(function (result) {
       return result;                            
    }, function (error) {
         console.error(error);
          return $q.reject(error);
    });  
  };

推荐阅读