如何进行$ http.post api调用以等待响应准备就绪

时间:2018-12-18 22:34:51

标签: javascript jquery angularjs

这是我下面粘贴的js脚本。当我单击按钮时,它会触发函数btnInitiateAPICall()并进行第一个API调用以获取用户数量。任何人都可以帮助我更正代码,以等待第一个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();
        }

1 个答案:

答案 0 :(得分:1)

将第二个呼叫放在.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);
       });

    }

}
相关问题