AngularJs: Tips for running functions synchronously

Is there a way to ensure that three services are executed synchronously in AngularJS? I'm facing an issue where my logic fails because the $http.get() services are running asynchronously. The goal is to read JSON fields from each service response, set flags based on the data validity, and then call the next service accordingly.

Sample Code:
  // Condition 1
if(item === false) {
            var product = Service1.get().then(function (response) {

                    // Logic for reading the JSON

                        // Setting the flag based on it..
                        item = true/false;
                    }




           //Condition 2
            if(item === false) {
                var call = Service2.get().then(function (data) {
                       // Logic for reading the JSON

                        // Setting the flag based on it..
                        item = true/false;
                    }
            }

            // Condition 3
        if(item === false) {
            var product = Service3.get().then(function (response) {

                    // Logic for reading the JSON

                        // Setting the flag based on it..
                        item = true/false;
                    }
        }
    }   



 Here, the problem is that code in *Condition3* is getting executed first then code in *Condition1* and *Condition2* which is causing the unexpected results.
It would be of great help if someone has the sample code in which three services are executed in a sequential manner.

Answer №1

Instead of making multiple $http requests in a chain within the success handler, consider approaching the issue recursively:

function handleRequests(array) {
   $http(array[0].config).then(function() {
       array[0].success();
       handleRequests(array.splice(0,1));
    }, function() {
       array[0].error();
       handleRequests(array); //note: no escape clause here
    });
}

The 'array' in this case contains objects with necessary configuration and callback functions.

{
   config :  {
    method: 'get',
    url: 'myurl'
   },
   success: function() {
       //implement actions
   },  
   error: function() {
      //handle errors
   }
}

Answer №2

It appears there are two methods to accomplish your goal based on the information provided:

  1. Adjust the $http.get function to asynchronous by setting async : true.

  2. Ensure proper request chaining so that each request is executed in sequence with its dependencies met before starting. This can be achieved by calling the dependent function within the callback of the preceding one.

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

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

Instructions for creating a function in TypeScript that accepts an array as user input and determining its length

Looking to develop a TypeScript function that can take an array of any type as input, calculate the number of elements present in it, and return the count. An example output would be: If user inputs: ["soccer", "basketball"] Then output: 2 Any suggestion ...

The JavaScript loop does not update the value of a number input field

In an effort to save and retrieve data from local storage, I have implemented a loop that iterates through various fields in a dynamic table row. The process involves saving the data to local storage, clearing the table rows, recreating them for data retr ...

Obtain latitude and longitude coordinates for the corners of a React Leaflet map

Currently, I am working with react-leaflet and facing a particular challenge: In my map application, I need to display pointers (latitude, longitude) from the database. However, retrieving all these pointers in one call could potentially cause issues due ...

Sublime Text 3 for React.js: Unveiling the Syntax Files

Currently, my code editor of choice is Sublime Text 3. I recently wrote a simple "hello world" example in React, but the syntax highlighting appears to be off. I attempted to resolve this issue by installing the Babel plugin, however, the coloring still re ...

Instant Pay Now Option for Your WordPress Website with PayFast Integration

I have encountered an interesting challenge that I would like some guidance on. My goal is to integrate a PayFast "Pay Now" button into a Wordpress.com blog, specifically within a sidebar text widget. The tricky part is that I need the customer to input th ...

Determine the type of element existing in the table cell

Currently, I am utilizing protractor to iterate through table cells in an attempt to verify the presence of a checked checkbox. var elements = element.all(by.css(columncssname)); elements.each(function (cell, index) { <--need to confirm if check ...

JavaScript's `setAttribute` function appears to be malfunctioning when used in conjunction

I am currently working in ORMB and have come across an input element that looks like this <input id="charVal" class="oraInput" oraField="charVal"> I've been trying to dynamically add an oraSearch attribute using JavaScript, but it doesn't ...

Steps for implementing a reset button in a JavaScript slot machine game

I need assistance with implementing a reset button for my slot machine game prototype written in JS. I attempted to create a playAgain function to restart the game by calling the main game function, but it's not working as expected. Do I need to pass ...

How can I adjust the spacing between slides in Slick?

Is it possible to achieve a layout like this using the slick slider? +-------+ +-------+ | | | | | +-------+ | +----| |----+ | | +-------+ The issue arises when trying to set margins between the slides ...

What is the best way to ensure that an object adheres to an interface during runtime validation?

Consider a scenario where I am dynamically deserializing JSON into a JavaScript object, such as the data received in a REST API response: const json = await response.json() Assuming that I have defined an interface for this object called ResponseRecord: i ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Sending a communication from PHP to Javascript following a successful file upload

Currently, I am in the process of creating a website that features a timeline similar to social media platforms. Uploading images is functioning as intended at the moment, although I still need to implement sanitization and validation checks - but that&apo ...

Updating the value within a nested array in a ReactJS application

Check out the working code here: https://codesandbox.io/s/broken-https-2i454?file=/src/App.js I'm currently using Material UI within my reactjs project and facing an issue updating the value entered in a textfield of a table using the onChange functi ...

Verifying whether an object has received any additional items

I am looking for a way to determine if an object has new subobjects. Specifically, I have an object with multiple nested objects and I want to check if the main object has any new objects added to it. Is there an existing method to achieve this? methods: ...

Unable to retrieve JSON data using Angular's HTTP GET request

I have retrieved JSON data from a database: {"user":"Rob",,{"user":"John",,{"user":"Chris",, etc etc I am implementing Angular to fetch the JSON and display it in an HTML table. <table> <tr> <th>Username:</th> </ ...

Is it possible to turn off trimming of angular templates?

Is it possible to disable the trimming of indention in my tree structure created using the select element? <select id="cat"> <option value="{{category.id}}" ng-repeat="category in categories">{{category | intent}}</option> </sele ...

Working with HTTPS in Angular: A guide to using $http

Can anyone provide guidance on how to handle https + cross-domain URL using $http? I managed to solve my issue using $.ajax, but I prefer using $http because I have an $http interceptor set up to automate certain processes. I've checked out related ...

I'm having trouble inserting text into a three.js scene

I recently started working with three.js and I'm experimenting with some basic code. However, I keep encountering the same error message. I was under the impression that I added the object to the scene after using the loader.load function, so I'm ...