Performing numerous HTTP POST requests within a single function in Angular

        $scope.observer_vel_data = function(){ 
        $scope.showOverlay('loadRefPubVel'); 
        $http({
            //Making the first http post request
            method:'POST',
            url:'/api/observer_vel_data', 
            data:$scope.payload_array,
        }).then(function successCallback(response){
            console.log('Successfully fetched velocity data from API endpoint!'); 
            //Making the second post request to fetch sentiment data
            $scope.sentiment_var = $scope.observer_send_sentiment();
            $scope.vel_var = response.data.velocity1;
        }, function errorCallback(response){
            // Handle API call failure
            $scope.addAlert({
                type: 'danger',
                msg: 'Failed to fetch data from API' 
            });
        }).finally(function(){
            console.log("hello");
            console.log($scope.sentiment_var);
            //Render the graph with fetched data
            $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
            $scope.hideOverlay('loadRefPubVel'); 
        });
    };

Trying to render a graph using data from two separate post requests, but facing timing issue with the second request data. Need help to resolve this. Details of the post requests and graph rendering commands are mentioned in the code.

        $scope.observer_send_sentiment = function (){  
        // $scope.showOverlay('loadRefSentiment');
        var data = { 
            "angularGroups":$scope.groups
        };
        // console.log(data);
        $http({
            method:'POST',
            url:'http://localhost:9612/sentiment_velocity',
            data:data
        }).then(function successCallback(response){
            var data = response.data;
            var json_obj = JSON.parse(data.replace(/\'/g,'"'));
            var sentiments = json_obj["sentiments"];
            // console.log(sentiments);
            $scope.update_sentiment(sentiments); 
            console.log(sentiments);
            return sentiments;
        }, function errorCallback(response){
            var errmsg = response.statusText; 
            console.log(response); 
            $scope.addAlert({
                type: 'danger',
                msg: 'API call failed (sentiment basic)' + errmsg,  
            });
        }).finally(function(){
            // $scope.hideOverlay('loadRefSentiment');
        });
    };

Answer №1

It seems like you're looking to make sure that the code within finally(...) runs only after the completion of the second request.

To achieve this, you must chain the HTTP request promises, where you return the promise of the second HTTP request from the success handler of the first request. Your code should resemble something like this:

$scope.observer_vel_data = function(){ 
    $scope.showOverlay('loadRefPubVel'); 
    $http({
        method:'POST',
        url:'/api/observer_vel_data', 
        data:$scope.payload_array,
    }).then(function successCallback(response){
        console.log('API Endpoint: vel data success!');
        $scope.vel_var = response.data.velocity1;
        return $scope.observer_send_sentiment();

    }).catch(function errorCallback(response) {
        //This catch will handle errors from both HTTP requests
        $scope.addAlert({
            type: 'danger',
            msg: 'API call failed' 
        });
    })
    .finally(function(){
        console.log("hello");
        console.log($scope.sentiment_var);
        //graph is rendered
        $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
        $scope.hideOverlay('loadRefPubVel'); 
    });
};

$scope.observer_send_sentiment = function() {
    return $http({...}).then(function(response) {
        //process the response
        ...
        $scope.sentiment_var = parsedResponseData;
    });
};

Keep in mind that the finally callback will always run regardless of errors. If you only want certain parts to run if no errors occur, consider adding another .then(function() {...}) instead.

EDIT: After reviewing what observer_send_sentiment does, it might be best to stick to the

.then(function successCallback() {...}, function errorCallback() {...})
syntax and have separate error callbacks for each request. If you plan to prevent execution of further .then(function() {...}) blocks upon encountering errors in the promise chain, remember to add return $q.reject(response) at the end of both error callbacks. Failing to use q.reject within error callbacks with the
.then(function successCallback() {...}, function errorCallback() {...})
syntax will resolve the promise rather than reject it.

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

Ways to reset a JQuery/JavaScript filter

I am currently working on a list of div items that are being filtered and sorted using JavaScript. Each item animates as it enters the screen, scaling up to its final size. However, when I apply filters using buttons, items that are already displayed do n ...

Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application. app.get("/admin/orders", (req, res) => { Q ...

What is the method for generating dynamic objects from configuration data with Ext JS?

Working with Ext Js to develop a dynamic web application can be quite challenging. When making an AJAX call to fetch data from the server, it's often unclear what the data will be until it is received. While some examples suggest adding dynamic object ...

The templateUrl directive with dynamic content

In order to showcase multiple popins using Angular on my homepage, I implemented the following: template1.html will appear as a popin. It worked after I corrected the .html file to display properly. <a class="vsn_alert-item-link" tooltip-special="tem ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

The issue of Ajax response not triggering the ng-click function

When attempting to pass data through an AJAX return, I encountered an issue with a function that writes an ng-click in Angular 1. The code snippet is as follows: $.ajax({ 'method': 'GET', 'url': base_url +&apos ...

Are moment.js and moment.php interchangeable?

Recently, I developed a JavaScript script utilizing moment.js and I am looking to mirror it using a cron job in PHP. In my search for moment.js equivalents in PHP, I came across this https://github.com/fightbulc/moment.php ...

Disable Jquery toolstrip while the menu is open

Currently, I am utilizing the jQuery toolstrip plugin in my project. I have a requirement to disable it whenever the sidebar menu is opened. Below are the HTML codes for my menu with li tags: <div class="sidebar-wrapper" id="sidebar-wrapper"> <ul ...

Tips for customizing the border radius style of the menu in Vuetify's v-autocomplete component

I am looking to customize the appearance of the drop-down list in the v-autocomplete component by adding a border-radius style, as depicted in the image below. The current design I have achieved closely resembles the visual shown below. Previously, I app ...

Choose the number that is nearest to the options given in the list

I am faced with a challenge involving a list of numbers and an input form where users can enter any number, which I want to automatically convert to the closest number from my list. My list includes random numbers such as 1, 5, 10, 12, 19, 23, 100, 400, 9 ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

Create a function in JavaScript that can generate a random number a specified number of times based on user input

I have been struggling to develop a JavaScript program that can generate a random number multiple times based on user input. Despite numerous attempts, I haven't been able to get it to work. Below is the code snippet I've been working with: f ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

What is preventing me from reading the input value in AngularJS using jQuery?

Just starting out with angularjs and I need help with this code sample: <ng-input theme='fumi' id='txtEmail' label='Email Address' icon='icon icon--fumi mdi mdi-select-all' style="font-size:medium;width:40%;"&g ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

issues related to implementing search functionality with react-redux

Just starting out with my first react-redux project which is a list of courses, but I have hit a roadblock with redux. I am trying to implement a search functionality based on this answer, and while I can see the action in redux-devtools, it's not ref ...

When using jQuery's .text() method, it updates the "source" content without affecting the actual DOM

Here is a scenario I am working on with jQuery: When the user clicks on a div An ajax call is triggered to save data in the database After receiving the callback, an update message is displayed <--everything good until here Now, if the user clicks on ...