这是我粘贴在下面的js脚本。当我单击该按钮时,它会触发函数 btnInitiateAPICall() 并进行第一个 API 调用来获取用户数量。但是使用我的代码,它不会等待firstAPI 完成执行并转到 InitiateSecondAPI 调用。任何人都可以帮助我更正我的代码,以等待第一个 API 调用完成,然后开始第二个 API 调用。
<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
block 中:
$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);
});
}
}
关于javascript - 如何进行 $http.post api 调用以等待响应准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53842117/