Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArray. I attempted to use a timeout for the HTTP requests in hopes of ensuring one request is fully processed before moving onto the next iteration of the for loop, but unfortunately, this approach did not yield the desired results. Any assistance would be greatly appreciated.

function commonService($http, $q) {
    return {
        getAboutContent: function() {
            var dataArray = [];
            var deferred = $q.defer();
            var idArray = ['about2', 'about3'];
            var count = 0;
            angular.forEach(idArray, function(id) {
                $http.get('server url/' + id).success(function(data) {
                    dataArray.push(data);
                    count++;
                    if (count == idArray.length) {
                        deferred.resolve(dataArray);
                    }
                }).error(function(error) {
                    console.log('error', error);
                    deferred.reject(error);
                });
            });
            return deferred.promise;
        }
    }
}

Answer №1

No one can guarantee which AJAX call will be completed first, as they are asynchronous. If you have a loop making 3 calls, the responses may not come in the same order. To ensure proper handling, you can return the ID from the server AJAX call and structure your code like this:

function customService($http, $q) {
    return {
        getAboutContent: function() {
            var contentArray = [];
            var deferred = $q.defer();
            var idList = ['about2', 'about3'];
            var counter = 0;
            
            angular.forEach(idList, function(id) {
                $http.get('server url/' + id).success(function(data) {
                    // Retrieve the index of "id" in the ID list
                    var idIdx = idList.indexOf(data.id);
                    // Insert the data at that specific index
                    contentArray[idIdx] = data;

                    counter++;
                    if (counter == idList.length) {
                        deferred.resolve(contentArray);
                    }
                }).error(function(error) {
                    console.log('error', error);
                    deferred.reject(error);
                });
            });
            return deferred.promise;
        }
    }
}

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

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

When jQuery is used to move rows between tables, it can interfere with

When moving rows between tables, everything seems to work fine. However, once the row is moved to the other table, all JavaScript functions related to that row stop working, and the reason remains unknown. The JavaScript code is simple - it involves takin ...

Including a pfx certificate in an Angular $http request

My current challenge involves utilizing an external API located at https://example.com/. Upon attempting to access this API, a prompt appears requesting a certificate. Fortunately, I possess the necessary .pfx file or it may be stored in my keychain as a . ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

Verify the information received from the ajax call to PHP

After incorporating all the guidance I received, I performed an update and here are the results: UPDATED CODE: $(document).ready(function(){ $("#submit").submit(function(e){ e.preventDefault(); var username = $("#username").val(); var ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

There is no way to avoid a PHP variable being displayed in a JavaScript alert box

It may sound silly, but I've spent hours trying to escape this PHP variable that contains post data: $post=array ( 'offers' => '90', 'pn' => '2', 'ord' => 'price', 'category_s ...

Error Occurs When Trying to Utilize Imported React Selector in React Actions Script

Desired Action: I am looking to utilize a state value within one of my action methods. Preferred Approach: Instead of directly referencing state.sale.oliver.data, I aim to abstract it by invoking my selector function, showingTest(state). Issue Encountere ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

If the href attribute is set to "#" or the target attribute is set to "_blank", then the <a> request cannot be prevented

I have a registration site that triggers a warning window whenever a user clicks on any link during the registration process. However, I want to exclude <a> tags with href="#" and target="_blank" attributes from this behavior. Essentially, I want to ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

Error: The function "text.toLowerCase()" is not defined

Whenever I execute the following code, I keep encountering this error message: Uncaught TypeError: text.toLowerCase is not a function const getVisibleExpenses = (expenses, { text, sortBy, startDate, endDate }) => { return expenses.fi ...

Is it possible to modify the sizes parameter of the GPUComputationRenderer?

Currently, I am utilizing gpuCompute = new GPUComputationRenderer( sizeX, sizeY, renderer ); for texture purposes. I am looking to update the values of sizeX and sizeY within this code snippet. However, after searching through the library, I have not been ...

In the console, a JSON string is displayed, however the PHP variable outputs as null

Below is the snippet of javascript code I am working with: $('.showEditForm').click(function () { var webpagefileID = this.id; if($('#editForm').css('display', 'none')) { $('#editForm').css ...

Using AJAX for redirection following a successful PHP post without any errors

I am fairly new to javascript, but I have successfully posted form data to a php file. However, I am now encountering an issue with validations on the php file. What I need is for this ajax request to display the error message if any validation fails and t ...