Tips for managing shared objects in asynchronous ajax requests

In a function called loadData, there are 5 parallel ajax calls being made to set data in the resulrArray with different dataType and their respective counts.

When the dataCollection() method is invoked, I am getting different count results for different dataTypes due to these simultaneous calls (each call sets a unique data type value).

How can I properly handle object population when making parallel calls OR should parallel ajax calls not be allowed for the shared object?

Here is some sample code for clarification:


app.factory("appfactory",['$q',function($q) {
   return {
       loadData:function(){
           return $q.all([this.f1(), this.f2(), this.f3(), this.f4(), this.f5()])
           .then(function(response){
               return response;
           });
       },
    }
}]);    

app.controller('appcontroller',['$scope','appfactory',function($scope, appfactory){
    appfactory.dataCollection()
        .then(function(response){
            for(var i=0; i<len; i++){
                var dataType = response.type;
                var dataCount = response.count;
                resulrArray.push({ "dataType":dataType, "dataCount":dataCount });
            }
        }); 
}]); 

Answer №1

From my understanding, a "parallel" ajax request is also known as an asynchronous request. The issue arises when the second request fires before the first request has had a chance to return a response and update the shared object. One solution is to use a synchronous request like this...

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous

While this method will ensure requests are sent in sequence, it is considered deprecated due to potentially locking the UI while waiting for responses.

Further Reading: Async and Sync https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Instead of using synchronous requests, consider implementing Promises. Frameworks like AngularJS handle this elegantly by waiting for the response of the first request before executing the second request within the ".then" property of the Promise. By utilizing the response to update your object and passing it as a parameter to the second Ajax request, you can prevent UI locking while still ensuring the second request waits for the completion of the first.

Learn More: Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

I hope this explanation helps clarify things for you.

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

Downloading a text file in Postman with a REST API in AngularJS is possible, but it may not work the same

$scope.newFile is the response I receive from the backend. In Postman, the response should be a text file, and it works as expected. However, when I try to access it in the browser, I encounter an issue. Cannot GET /Organizer/%7B%22data%22:%22id/tnam ...

Is Swiper carousel navigation secretly operating without being seen?

I've got a website that utilizes the Swiper carousel from SwiperJS, find it here: An issue I am facing is that the navigation elements are invisible but functional, with the pagination feature unaffected. This peculiar behavior is observed only in Sa ...

"Encountered difficulty in retrieving the width of an element upon refreshing the

I have come across a puzzling situation with my code that involves determining the width of a block element. Here is an excerpt from the code snippet: //get the largest block: if no block, apply to first block var previous = $('.block-grid .block-gr ...

Concerns arise with the swal destroy functionality

I have a working code for the Swal function, but when I click cancel without entering any information, it still triggers the AJAX call, which is not desired. $(document).on('click','.addon',function() { Swal.fire({ title: &apo ...

Develop JavaScript code to handle multiple JSON objects

I have values stored as objects in an array and I would like to create a JSON structure similar to the one shown below. I have provided both HTML and JS code, but I am struggling with writing the proper javascript to generate this JSON structure. Can someo ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Passing values between PHP and jQuery using Ajax to compare with a variable is a common task in web development

I'm struggling to get my PHP and jQuery script to work properly. The goal is to pass a value through Ajax, have PHP check it to see if it matches and increment the score by 1. Here is the code I've written: <?php $score = "1"; $userAnswer = ...

`The $scope variable is confined within the function's scope, hence its functionality is restricted and

Here is the layout of my page: <li class="dropdown"> <ul class="submenu"> <li><a href="../Account/#/PersonalInfo" ng-click="SetActiveMenuForPersonalInfo();">@Translate("MY_ACCOUNT")</a></li> </ul> </li> Wit ...

Execute button click automatically upon page loading in AngularJS

I'm trying to figure out how to automatically trigger a button click on an AngularJS page when the page loads based on a querystring value. In a traditional asp.net web forms page, I could easily handle this scenario by calling Button1_Click(sender,e) ...

Unable to generate UUID for the Angular ui-select field entry

Within my Angular codebase, I have a ui-select field where the entries are stored as an array object. However, every time I attempt to add or remove something, I encounter the following error: Cannot create property 'id' on string 'xxx&ap ...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

How to Make Page Slide in Either Direction Based on User Click Location

Although the title of my question may not be very descriptive, I am essentially trying to implement a functionality where a page will slide right if a user clicks a link to the right of their current active link, and slide left if they click a link to the ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

Tips for utilizing multiple marker properties on a single marker in Vue Leaflet

Is there a way to utilize both rotationAngle (vue2-leaflet-rotatedmarker) and duration (vue2-leaflet-movingmarker) in a single marker? For example: <l-marker :lat-lng="run.currentPoint.latLong" :icon="run.currentPoint.icon" :rotati ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...

Save the script source in an array

When it comes to loading assets such as js & css from the next page and storing them in an Array, I have implemented a method where I iterate through the document and store the JavaScript links separately. It currently looks like this: 0:{images: Arra ...

Angular animations are failing to function in the Visual Studio 2017 template

I am facing a challenge with incorporating animations in Angular 2 using Visual Studio 2017. I believe there must be a simple solution that I am overlooking at the moment. My goal is to animate certain elements and I have been testing the animations by tri ...

When I employ ngroute, the Angular section in the html page does not display

I am looking to implement a fixed menu named "fixed_admin.html" on my website: <!DOCTYPE html> <!-- saved from url=(0069)https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/ --> <html lang="en"><head><meta htt ...

Explore various query strings without the risk of JavaScript overwriting references to previous variables

Seeking to extract data from this specific website, I've developed a javascript function that effectively retrieves the necessary information: const total_planning_applications = 39437 const min_value = 39407 var superArray = [] var i = 1 window.loca ...

How can you automatically show the current time upon entering a page using React Native?

Is there a way to automatically display the current time when a user enters the page? I currently have code that only shows the current time when the TouchableOpacity is pressed, but I want it to update automatically as soon as the user arrives on the Ne ...