首页 > 解决方案 > 如何使 $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();
        }

标签: javascriptjqueryangularjs

解决方案


将第二个调用放在一个.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);
       });

    }

}

推荐阅读