Executing asynchronous code in a sequential manner

I'm encountering a problem. I have an AngularJS function that calls another AngularJS function which includes a POST request. The issue is that this POST request always fires last, once the first function has completed. It doesn't execute sequentially.

        servicePOST.send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
             "date":d
             }).then(function(result) {
        console.log(result);

         });

Could someone please help me understand this behavior and suggest any workaround? I need all HTTP requests to be executed sequentially. How can I implement this in the code provided? Thank you in advance!

Answer №1

Utilizing this method may provide assistance to you

const CustomFunction = function( $scope, customPOST, ServiceB,  ServiceC )
    {
        // First step
        customPOST
            .send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
             "date":d })// Request #1
            .then( function( result )                // Response Handler #1
            {
                 $scope.dcrlocked = result.dcrlocked;
                // Second step
                ServiceB                             //AnotherService Call
                    .send({})        // Request #2
                    .then( function( result  )              // Response Handler #2
                    {
                       $scope.leaves = result.leaves; 
                        // Third step
                        ServiceC
                            .send({})      // Request #3
                            .then( function( result )          // Response Handler #3
                            {
                               //$scope.holidays = result.holidays;
                            });
                    });
            });
    };

Answer №2

It seems like your situation involves a page where different sections are dependent on each other and served through separate http requests.

To address this issue, you can initiate the subsequent http request from the success callback of the initial http request, creating a chain of requests. For example:

servicePOST.send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
         "date":d
         }).then(function(result) {
     $scope.dcrlocked = result.dcrlocked;
     $scope.leaves = result.leaves; 
     //$scope.holidays = result.holidays; 
     //initiate another http request as shown below.
     servicePOST2.send(url,{data or data from previous request}).then(function(){
            // initiate another http request and so forth.
        })
     });

By making all http requests within the success callbacks of preceding requests, you ensure a sequential flow of requests.

UPDATE

You can leverage $promise in your secondary function that handles the post request. For instance:

    var deferred = $q.defer();
    servicePOST.send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
        "date":d
    }).then(function(result) {
        $scope.dcrlocked = result.dcrlocked;
        $scope.leaves = result.leaves; 
        //$scope.holidays = result.holidays; 
        deferred.resolve(result);
    });
    return deferred; // return deferred from your function.

Remember to inject $q into your controller and pass it to the subsequent function. This adjustment enables the post function to execute synchronously. Please confirm if this aligns with your requirements.

Answer №3

Simply put, it's not possible. Javascript operates in a non-blocking manner as part of its design, so you'll have to explore promises or incorporate nested callbacks to achieve the desired functionality.

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

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

A step-by-step guide on implementing a callback function

I am eager to incorporate a callback into this script - specifically the third callback onSlideChangeStart(swiper) found at http://idangero.us/swiper/api/#.V9CMp5grJlY. Since I have never worked with callbacks before, I am unsure of where to begin. In es ...

including a callback in a loop

I am attempting to have jQuery delete an element after it has gone through a series of other functions, however the following code executes the remove() command before the for loop runs any iterations. function waves(){ for(i=0;i<=10;i++){ ...

Issues with uploading files in NodeJs using express-fileupload are causing errors

I created a REST API in NodeJs for File Upload which is functioning correctly, however I am facing an issue. When I upload more than 2 images, only 2 or 3 get uploaded and sometimes one gets corrupted. I suspect that the loop is running too fast causing th ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Is there a way to utilize ajax to submit a form and upload a file to a spring controller?

I have a form with four fields: file, name, type (as a string), and taskInstanceId. <form> <table id="documentDetailsTable"> <tr> <td>Document Type: </td> <td><select id="documentType" ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

jQuery MaskMoney - position input at the start of the field

Check out this jsfiddle I created to showcase the issue I'm facing. Whenever I click on the input field, the cursor automatically goes to the end. This means that I have to start typing cents before dollars, which is not the behavior I want. My desire ...

I need to see the image named tree.png

Could someone assist me in identifying the issue with this code that only displays the same image, tree.png, three times? var bankImages = ["troyano", "backup", "tree"]; jQuery.each( bankImages, function( i, val ) { $('#imagesCon ...

Jquery Validate doesn't consistently give a positive response

Having a button that triggers the jQuery validation plugin poses an issue where it consistently returns true, except when the fields are left empty. The rules set for validation seem to be disregarded. DEMO http://jsfiddle.net/sw87W/835/ $(document).read ...

Vue.js variable routes present an issue where the Favicon fails to appear

I've successfully set my favicon in the index.html file for my Vue webpack SPA. It displays properly when I visit the main site or any standard route, but it fails to show up when I navigate to a dynamic route (path: "/traduzione/:translation"). I&ap ...

Stopping npm private organization from releasing public packages

Is there a method to restrict the publication of public packages within an npm organization? It appears that this scenario would often arise (ensuring that no member of an organization accidentally publishes a package as public when it should be private b ...

Customize the CSS for a Material UI popover styling

I am currently working with a Material UI popover and attempting to apply CSS styles to it. This is the code for my popover component: import React, { memo, useCallback } from 'react'; import PropTypes from 'prop-types'; import { ...

Combining arrays of objects that contain nested arrays of objects using JavaScript along with libraries such as lodash or Underscore

Attempting to combine two arrays of objects using the lodash JavaScript library, however, encountering an issue where the Subcategories property containing another array is not being merged. Here are the arrays to be combined: var menu1 = [ { "PageNa ...

Create a personalized and distinct name following the submission of data into multiple text fields either through Nuxt/Vue or by utilizing pure JavaScript

In my new app, users can register packages and then participate in a ballot session where the package will be assigned to someone else. To make this process smoother, I want each ballot session or box to have a unique Ballot ID attached to it. For example ...

Utilizing jQuery to toggle a dropdown box based on multiple checkbox selections

After conducting a search, I came across a helpful resource on Stack Overflow titled Enable/Disable a dropdownbox in jquery which guided me in the right direction. Being new to jQuery, I found it useful to adapt code snippets to suit my needs. Now, my que ...

Creating a Gmail share button in AngularJS: A step-by-step guide

I created a messaging web application using AngularJS, and I successfully added functionality to share messages via email using the "mailto" link. However, this method only works if the user has an email client installed. Now, I am looking for a solution ...

Preventing a user from navigating away from a page without completing a specific action, such as clicking a submit button

I am in the process of developing an interactive quiz platform. The quiz includes a timer that begins counting down once the user initiates the quiz. Upon completing the quiz, the user is expected to submit their answers. If the user runs out of time, th ...