The sequencing of asynchronous execution in AngularJS when using $http.get

After spending a significant amount of time coding in AngularJS, I finally reached a point where I felt comfortable and productive. However, there is one aspect that continues to confuse me:

Specifically, within my project, I am required to retrieve data using $http.get and a RESTful API server. This is where I encountered my first roadblock. I implemented promises ($q.defer, etc.) in functions that process essential data to move forward, believing I had resolved the issue.

Yet, when looking at this code:

$scope.getObservationsByLocations = function() {
        var promise = $q.defer();
        var locationCount = 0;

        angular.forEach($scope.analysisData, function(loc) {   // for each location
            $http.get($scope.api + 'Device?_format=json', {     // get all devices
                params: {
                    location: loc.location.id
                }
            }).then(function (resultDevices) {
                var data = angular.fromJson(resultDevices);
                promise.resolve(data);
                // for each device in this location
                angular.forEach(angular.fromJson(resultDevices).data.entry.map(function(dev) {
                    http.get($scope.api + 'Observation?_format=json', {     // get all observations
                        params: {
                            device: dev.resource.id
                        }
                    }).then(function (resultObservations) {
                        var observations = angular.fromJson(resultObservations);
                        // for each observation of that device in this location
                        angular.forEach(observations.data.entry.map(function(obs) {
                            $scope.analysisData[locationCount].observations.push({observation: obs.resource});
                        }));

                    })
                }))
            });
            locationCount++
        });
        return promise.promise
};

I find myself puzzled by the order in which commands are executed. Even with the debugging feature in Webstorm IDE, it seems unclear why the commands follow a sequence that I cannot comprehend.

In theory, everything within the forEach loop should execute before reaching the return statement due to the chained $http.get requests via .then(). However, during debugging, the function appears to iterate over locationCount++ and return the promise even before delving deeper (after the initial .then()).

Is there a gap in my understanding of this aspect of AngularJS, or is this simply poor practice that warrants exploring alternative solutions?

If necessary or of interest, the objects are derived from sources such as

Answer №1

JavaScript is typically used to create single thread applications, although there are discussions about whether it is guaranteed to always be that way.

In the real world and real browsers, your code will run as a single thread, which is also responsible for rendering CSS and HTML in some browsers like Firefox.

When an asynchronous call is made, such as:

$http.get($scope.api + 'Device?_format=json', { 

it essentially tells the program to delay execution until it is ready to fetch remote data.

After completing the current task with return, the program will then proceed to retrieve the remote data.

To see this in action, you can check out this fiddle:

console.log(1);

for (var i=0;i<1000000;i++) setTimeout(function(){
    console.log(2);
},0);

console.log(3);

You'll notice a spike in the output when the for loop registers the asynchronous calls via setTimeout. However, the number 3 is still printed before 2 because the task is not complete until after 3 is displayed.

Answer №2

Since the $http.get function is asynchronous, the timing of its completion can vary depending on factors such as the size of the retrieved data. This unpredictability results in no definite order in which the requests will be completed.

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

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

Obtaining latitude and longitude data from Google Maps JSON output using NodeJS

Can someone help me with extracting the lat and lng from the location object in this JSON response from Google maps? I attempted response.body.results[0].geometry.location.lat but encountered a ReferenceError: results is not defined. Here is the content of ...

Guide to passing JSON Data as a response in Vue.js version 2

Currently working on a Vue.js website that interacts with an API (route -> /api/**). However, I am struggling to figure out the process of sending JSON responses. Is there a similar method like res.json() in Vue.js as express.js has? ...

The EJS templating system

I am currently working on a node.js project and I have an ejs template file that utilizes templates for the header and footer. The structure of template.ejs is as follows: <%- include(header) %> main content <%- include(footer) %> <script ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

An effective method for sorting a dictionary by its values and converting it into a string

I currently have a dictionary consisting of string keys paired with integer values. for word in coocc[query]: resp[word]=coocc[query][word] {"share": 1, "pizza": 3, "eating": 1,...} To achieve the desired outcome, I am aiming to sort by value and ...

What role do colors and tables play in Javascript?

Preparing for my upcoming Web Development exam, I stumbled upon an intriguing question:https://i.sstatic.net/m9T0F.png Here's how I tackled it: function pallete() { var components = ["00", "33", "66", "99", "CC", "FF"]; var conte ...

How to save an image in Internet Explorer browser without opening it automatically

Is there a way to download an image in Internet Explorer using the <a> tag without it opening in a new tab? Since IE does not support the HTML5 <download> tag, I am looking for a solution to directly download the image instead of opening it. ...

What is the best way to organize AngularJS directive for complex form fields structure?

Utilizing AngularJS for managing administration forms has been a smooth experience so far. The capability to bind view and model, along with the ease of incorporating validation, are features I appreciate. However, my attempt at streamlining code by implem ...

Overlay a small image on top of a larger background image using canvas, then merge them into a single set of pixel

Is there a way to combine a smaller image with a larger background image on one canvas while allowing the smaller image to move around? I'll need to save the original background pixel data so that each frame can be redrawn with the overlay in its upda ...

retrieve a value from an eventListener embedded within a forof iteration

How do I pass the coin object returned from the displayCurrencies function to the getCoinId function as a parameter for making an API call to retrieve specific coin data? This is the function created to return the value: let returnID = (value) => { r ...

Use jQuery to dynamically update a text field within a table row based on a selection from

My understanding of JS and jQuery is not very strong. This is the HTML Output I created using a foreach-loop: $('#ProjectOfferPosition0IsystemTypeVariantId').on('change', function () { var prices = []; prices[1] = 500.00; ...

The iPhone API for Rails login is unable to process parameters in JSON format

API endpoint: http://www.example.com/users/sign_in Parameters: {"user":{"login":"test","password":"test123$"},"commit":"Login"} After submission: Started POST "/users/sign_in" for 127.0.0.1 at 2015-04-10 17:10:20 +0530 Processing by SessionsController ...

Issue with Pure Javascript FormData upload involving files and data not successfully processing on PHP end

My file upload form follows the standard structure: <form id="attachform" enctype="multipart/form-data" action="/app/upload.php" method="POST" target="attachments"> <!-- MAX_FILE_SIZE must precede the file input field --> <i ...

Utilizing Angular's ng-if to dynamically adjust Twitter Bootstrap's column size with col

Here is the code snippet: left block right block This code displays the left block on the left side of the screen and the right block on the right side, adjusting for different screen sizes. If the screen i ...

Analyzing an External File containing JSON formatted columns

As a newcomer to this site, I welcome any feedback on my approach. My current project involves exploring the 6 degrees of Kevin Bacon by utilizing an external CSV file to create an unweighted graph. The goal is to allow users to determine the shortest path ...

Using an alias to call a function defined in a separate module in TypeScript

The following code snippet is from the v4.js file located inside the uuid folder within Angular's node_modules: var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { ...

"Enhancing communication with PHP-powered private messaging through AJAX technology

Hey, I'm interested in creating a basic private messaging system using PHP, MySQL, JavaScript, and possibly AJAX. However, I'm unsure of how to begin. Can anyone recommend any user-friendly tutorials for building one? It doesn't have to be e ...

Do HTML attributes that are customized without the data-* prefix considered valid?

When it comes to AngularJS, the data- prefix is an option but not a requirement in their examples. Should I decide to include the data- prefix in my project, and what are the benefits of doing so? Will my HTML still be valid even if I choose not to make u ...

What is the most effective approach for handling JSON data from URLs in a professional manner?

Hey there, I'm facing a dilemma on how to efficiently handle data retrieved from various URLs on my website. My website allows me to fetch JSON data from multiple URLs. For instance, there's a page full of posts related to a specific group with ...