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

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js. To begin with, my web3 is establishing a connection to the HardHat forked server. The first step involves setting ...

What are the steps to incorporate an iframe containing uniquely designed XML content?

I'm currently working on a website project for a client who specifically wants to include news from the BBC. Despite spending 3 hours searching online, I haven't been able to successfully insert an XML file into an iframe and style it to the clie ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Tips for effectively invoking a method in a Vue component

As a Vue2 beginner, I am currently working with the Vue CLI and following the structure generated from it. My goal is to submit form data, but I keep encountering a warning and error: [Vue warn]: Property or method "onSubmit" is not defined on the insta ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template). After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mut ...

What methods are available to load sections of a complex SVG shape asynchronously?

I'm currently in the process of creating a website with a geographic map built using SVG, pulling data from OpenStreetMap. Due to its large size and potential for transformations such as zooming and moving, only a portion of it will be visible on the ...

Can someone tell me what comes after my nextElementSibling in this specific scenario?

I am puzzled by the usage of nextElementSibling in this code. Can someone provide an explanation on what exactly it is and where it should be used? Thank you in advance! Also, my code seems to be malfunctioning as I keep receiving an error message that s ...

Exploring the benefits of browser caching JSON data in AngularJS

Currently, I am in the process of developing an application using the AngularJS framework. The Issue at Hand: Whenever I navigate away from my application to a different domain or page and then attempt to return using the history back button, I find that ...

Can the AngularJS icon adapt to different lists?

I'm currently developing in AngularJS / Jade and I need to implement functionality where an icon changes when a user clicks on something. The code I have right now looks like this: a(onclick='return false', href='#general', data-t ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP. For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/ function autoPopulate() { var cast = "John Wayne, Julia Roberts, Kevin Spacey"; cast = cast.split(', '); ...

Transferring values with jQuery

I attempted to customize the appearance of the select dropdown options, but unfortunately, the value of the options is not being transferred to the new jQuery-created class. Due to this issue, I am unable to achieve the desired outcome. The expected behavi ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

What could be causing my textarea-filling function to only be successful on the initial attempt?

Programming: function updateText() { $("body").on("click", ".update_text", function(event) { $(this).closest("form").find("textarea").text("updated text"); event.preventDefault(); }); } $(document).ready(function() { updateText(); }); H ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

Is it possible to have two router.js files within a single Angular project?

Encountering a dilemma in my Angular UI routing project with rendering the view. Contemplating using two router.js files. Is it feasible to include two router.js files in one project? What drawbacks might arise from this approach? ...

Efficiently converting HTML object data into plain text using RegExr in ReactJS and JavaScript

Is there a way to convert an object in JavaScript/ReactJS into a string? For instance, consider the following object: { article: '<p class="md-block-unstyled">First text...</p><p>Second text></p>' } I am looking to ...