angularjs - 在 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()
解决方案
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);
});
};
推荐阅读
- haskell - 功能依赖和奇怪的刚性类型变量错误
- azure - Azure DevOps Deploy WebApp 任务中的应用设置和配置设置有什么区别?
- python - 使用 pyodbc 连接到在 docker 上运行的 Postgres
- azure - 模型训练反复失败
- php - PHP PDO 准备好的语句未执行
- angular-cli - 在 Angular CLI 项目结构中创建 ionic 4 应用程序
- javascript - 如何在innerHTML onclick事件中动态传递字符串参数
- actionscript-2 - 数组返回未定义(动作脚本 2)
- c# - SqlConnection 建立后的 SqlTransaction vs TransactionScope
- sql - postgres 在“主”表上加入“其他”表,该表有 2 个对“其他”表的引用