javascript - 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 没有更新,而是使用旧值而不是返回的更新值。
处理这个问题的最佳方法是什么?
解决方案
如果 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
推荐阅读
- html-lists - 是否可以在 OpenLayers 中拖动图层?
- rxjs - 当 observable 完成时,我应该如何发出单个值?
- javascript - 本机javascript中一些短语的含义
- javascript - 获取电子应用程序外的插入符号位置
- java - 重新打开以前关闭的 Window Java
- php - 如何在 Opensuse 风滚草中安装 PHP8 XDebug?
- amazon-web-services - AWS Dynamo DB:如何在没有 GSI 的情况下进行有效设计
- javascript - Vuelidate匹配/sameAs但忽略大小写敏感?
- flutter - Flutter:InkWell 在 Card 中完全不起作用
- python - 如何在 mac os x 上使用 gunicorn 和 python3.8 而不是 python3.9?