javascript - 如何进行 $http.post api 调用以等待响应准备好

标签 javascript jquery angularjs

这是我粘贴在下面的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/

相关文章:

Javascript从匿名函数访问外部对象属性

angularjs - 在 Angularjs 列表中显示 TimeSpan 类型数据

Javascript:对于各种浏览器中的 HTML5 API/ECMAScript5/ECMAScript6,是否有等同于 caniuse.com 的网站?

javascript - 动画 1400 个 Raphael.js 对象的不透明度会影响动画性能

javascript - 如何在动画滚动中将整个页面从链接滚动到 75%

javascript - 通过从 URL 获取百分比在 Django 中添加进度栏

javascript - 当有最小宽度时,如何使元素中心(水平)固定位置?

javascript - 循环以从对象数组中收集所有图像属性

javascript - 对 ng-grid 中的基础数据进行排序

javascript - 如何检查 JavaScript 中是否定义了闭包?