javascript - 如何使 $http.post api 调用等待响应准备好
问题描述
这是我粘贴在下面的 js 脚本。当我单击按钮时,它会触发函数 btnInitiateAPICall() 并进行第一次 API 调用以获取用户数。但是使用我的代码,它不会等待 firstAPI 完成执行并转到 InitiateSecondAPI 调用。任何人都可以帮助我更正我的代码以等待第一个 APIcall 完成,然后从我的第二个 APIcall 开始。
<button type="submit" class="btn btn-primary left" id="btnSubmit"
ng-disabled="working" ng-click="btnInitiateAPICall()">
submit
</button>
<img width="30" height="30" class="progressgif" style="display:none"
alt="spinner" src="../Images/spinner.gif">
$scope.btnInitiateAPICall = function () {
if ($scope.selection == '' || $scope.selection == undefined) {
alert("Please select one option from dropdown");
return;
} else {
var count=FetchNumberOfMatchingUsers($q, $http) //this call should wait until the count is returned before it goes to next line
InitiateSecondAPICall(count);
}
}
function FetchNumberOfMatchingUsers($q, $http) {
console.log("starting FetchNumberOfMatchingUsers");
$('.progressgif').show();
return $http.post("/api/UserRecords/GetUserCount", {
Instance: $scope.selection,
}).then(
function (response) {
$scope.count = 0;
$scope.count = response.data;
return response.data;
}
).catch(
function (response) {
return $q.reject(response);
});
$('.progressgif').hide();
}
解决方案
将第二个调用放在一个.then
块中:
$scope.btnInitiateAPICall = function () {
if ($scope.selection == '' || $scope.selection == undefined) {
alert("Please select one option from dropdown");
return;
} else {
FetchNumberOfMatchingUsers()
.then(function(count) {
//this call should wait until the count is returned before it goes to next line
InitiateSecondAPICall(count);
});
}
}
推荐阅读
- elasticsearch - 如何在 elasticsearch 上仅添加新文档或更改的文档?
- python - 在 CMD 或 Powershell 中查看使用 Python 执行的命令的历史记录
- python - 是否有运营商指定索引“不小于0”?
- python - 尝试在 spyder 上使用 GLPK 运行时出错
- r - Is there a way in R / ggplot2 of re-ordering the legend to match it's line position?
- python - Python Luigi:处理缺失依赖的有效方法
- swift - 在 ForEach 循环中从 [Any?] 获取项目以显示文本
- symfony - 在 Symfony 5 中使用 composer 安装 EasyAdmin 的问题
- agora.io - 如何修改示例应用程序以使 RTMP 注入视频在 UI 中排在首位?
- typescript - 如何用 jest 测试对同一函数的特定调用序列