Ways to ensure that the $http.post api call waits for the response to be fully prepared

Below is the JavaScript code that I am using. When I click the button, it calls the function btnInitiateAPICall() which makes the first API call to get the number of users. However, my code does not wait for the first API call to finish before moving on to the InitiateSecondAPI call. Can someone help me correct my code so that it waits for the first API call to complete before proceeding with the secondAPIcall?

<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();
        }

Answer №1

Move the second API call inside a .then block:

$scope.btnInitiateAPICall = function () {

   if ($scope.selection == '' || $scope.selection == undefined) {
        alert("Please choose an option from dropdown menu");
        return;
    } else {

       FetchNumberOfMatchingUsers()
       .then(function(count) {
            //this call will wait for the count to be returned before proceeding
           InitiateSecondAPICall(count);
       });

    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript rearrange array elements

Currently, I'm attempting to move the values of an array over by a random amount. For instance: var array = [1,2,3,4]; var shiftAmount = 1; The goal is to shift the array so that it looks like [4,1,2,3] ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

jQuery: Automatically scroll to the end of the div based on the height of the content within

I have successfully developed a chat feature that is functioning perfectly. However, I am encountering an issue with making my div scroll to the bottom. The height of the div is calculated as calc(100% - 60px);. This particular div retrieves messages from ...

Is it possible to achieve a height transition using CSS instead of relying on JavaScript

I created these custom cards using a combination of HTML, CSS, and JavaScript. However, I've noticed that the height transition animation is not as smooth as I'd like it to be, especially on certain pages. Is there a way to achieve this animation ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Error: Unable to locate module: Material-UI - Please check the path and try again

Encountering this error: Error message: Failed to compile ./node_modules/@material-ui/core/Modal/Modal.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'C:\Users\rifat\ ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

Persistent navigation once fullscreen banner is completed

I have a full screen header on my one-page website. Below the hero section is the navigation element, which I want to be fixed after scrolling past the height of the full screen. Here's what I currently have in terms of code. HTML: <div id="hero" ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

What is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

What is the best way to make ng-style append to a pre-existing style?

I am facing an issue with my custom popover directive and another custom directive that uses it. I am attempting to use ng-style to adjust the width of the popover. Below is a code snippet from the directive's html template: <div my-custom-popover ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

What is the best way to maintain the connection of this keyword to the window object in webpack?

I recently converted my AngularJS application to es6 using webpack and the import/export syntax. Everything is running smoothly, except for the this keyword. Due to webpack wrapping all of my code into iife functions during compilation (modules), the thi ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

The issue with the full postback in the updatepanel is triggered by utilizing JavaScript on the button's onclick event within

During my testing, I encountered an issue with buttons inside a repeater within an update panel. When adding asyncpostback triggers for the buttons using <Trigger></Trigger>, an error is generated indicating that the button could not be found. ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...

I am interested in placing focus on a specific grid column within Kendo

When I lose focus from the table columns, I want to check their values. I created a demo to demonstrate this concept for better understanding. You can view it by following this link: http://jsbin.com/oqeral/16/edit In my implementation, if a column's ...