Restricting concurrent asynchronous $http get requests in Angular程序

I've set up a page displaying a table of IP addresses connecting to a media stream. I've linked them to a database that includes location information and have managed to serve duplicate IP requests from cache to lighten the load. However, the page crashes with an Error: Insufficient Resources message when too many requests are made simultaneously. I attempted batching using this library, but received a deprecation warning about

Synchronous XMLHttpRequest on main thread
, and it didn't seem to alleviate the issue either. How can I restrict the number of searches performed at once? I don't want to limit it to one at a time as it would be too slow otherwise. Here is the relevant code:

angular.forEach($scope.results, function(conn, key){

    $http.get("addrinfo.cgi?action=get&addr="+conn.ip, { cache: true}) //$scope.results is a list of IP addresses
                    .then(function(ipLocation) {
                        console.log(ipLocation);
                        var locationResults = ipLocation.data; 
                        conn.country = locationResults.country;
                        //... more assignments
                    });
                });

Edit: I'm encountering difficulties implementing Paul's solution. I keep receiving a RequestManager is undefined error. The structure of the code looks like this.

angular.module('ip-module', [
'app.controller',
'app.filter',
'app.factory'
]);

app.controller('ip-analysis', function($scope, $http, $q) { ... })

.filter('customNumFilter', function() { ... })

.factory('RequestManager', ['$http', '$scope', function() { ... 
}]);

Answer №1

If you want to efficiently handle multiple requests, consider creating a manager to manage them. This manager can monitor the number of ongoing requests and redirect any excess requests to a queue for later processing. Once a request is completed and there are available slots, the next request from the queue can be executed.

import copy

angular.module('your-module', []) 

.controller('Controller1', function(){
  .... 
}) 

.controller('Controller1', function(){
  .... 
})

.factory('RequestManager', function(){
  var manager = {
    limit: 10,
    queue: [],
    cache: {},
    requests: 0,
    sendRequest: function(conn){
      if(manager.requests < manager.limit){
        if conn.ip in manager.cache.keys():
          conn.update(manager.cache[conn.ip])
        else:
          manager.runRequest(conn);
      }else{
        manager.queue.push(conn);
      }
    },
    runRequest: function(conn){
      manager.requests++;
      $http.get("addrinfo.cgi?action=get&addr="+conn.ip, { cache: true})
        .then(function(ipLocation) {
            console.log(ipLocation);
            var locationResults = ipLocation.data; 
            conn.country = locationResults.country;
            //... more assignments
            manager.cache[conn.ip] = copy.deepcopy(conn) #use deepcopy to make sure the value is not overwritten in the $scope
            runNextRequest();
        }, function(error){
          runNextRequest();
        });
    },
    runNextRequest: function(){
      if(manager.requests > 0){
        manager.requests --;
        if(queue.length > 0){
          manager.runRequest(queue.shift());
        }
      }
    }
  }
  return manager;
}

To implement this in your controller, you can use the following code snippet:

angular.forEach($scope.results, function(conn, key){
  RequestManager.sendRequest(conn);
}

Remember to customize the code according to your needs and test it thoroughly before deployment.

Note: Please proceed with caution as I have not had the opportunity to verify this code for potential errors.

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

Enhance the list visualization in Next.js by efficiently transferring data from child components

In my Next.js Page component, I have a setup similar to the following: export default function Index({ containers }) { const [containerListState, setContainerListState] = useState(containers); const updateContainerList = (container) => { contai ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

Implement the Bootstrap datetimepicker functionality for the specified div element

The date picker successfully functions when I assign the id to the input tag as shown below: <div class="col-sm-4" id="datepicker"> <input type="text" class="form-control" id="inputDate" placeholder="Date"> <span class="glyphicon gl ...

Learning more about the functionality of ui-router, particularly how the ui-sref directive can be used to navigate to

Here is an example of the HTML code: <li class="list-group-item" ui-sref="contacts.detail({id:4})"> <span class="badge" ui-sref="contacts.selected">14</span> Cras justo odio </li> When contacts.selected is clicked, it w ...

AngularJS extension known as 'ngclipboard'

I've been attempting to utilize a plugin called ngclipboard in Angular, but something seems amiss as it's not functioning as expected. There are no error messages, however, the text from the input box is not being copied to the clipboard. To see ...

Is it possible to utilize $(document).ready() within an ASP.NET page?

I am encountering an issue while attempting to use $(document).ready() as shown in the image above. What steps should I take to troubleshoot and resolve this problem? Update 23/05/2011 10:54 A new insight has come to light. The page I am working on inher ...

Monitoring the inclusion of a new item within the database

I am utilizing a Firebase Realtime Database where users have the ability to perform the following actions: add an item to the database update an item in the database Currently, I have a function that monitors a specific location within the database. ...

Exploring methods for obtaining a string from the server following an Ajax request

My experience with AJAX has been interesting - sending data from the client to the server was surprisingly easy, but I've been struggling with receiving data back from the server. What I need is to send some parameters to my ASP server and receive a ...

Create a new storefront JavaScript plugin for Shopware 6 to replace the existing one

I am attempting to replace an existing JavaScript plugin in Shopware 6. However, the code within the plugin file does not seem to execute. Here is my main.js: import MyCookiePermissionPlugin from './plugin/my-cookie-permission/my-cookie-permission.pl ...

Unexpected behavior encountered when using onClick in a material-ui List component containing Buttons

Looking to implement a customized list using React and Material-UI, where each item features a Checkbox, a text label, and a button. The onClick event for the Checkbox should be managed by a separate function from the onClick event for the Button. Encount ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Underlining.js - Evaluating differences between two arrays containing objects

Looking to cross-reference two arrays containing objects with different key names, utilizing underscore... array1 = [{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0829586..."], first_name:"asad"}, {email:"<a href= ...

The <select> element in AngularJS 1.5 is showing the dropdown at unexpected moments, but only on iOS 10 devices

From the title, it's evident that this bug is both intriguing and frustrating. The issue lies with a regular select element in an Angular partial containing the following code: <select ng-options="availweek.weekNumber as availweek.weekNumber for a ...

What is the best way to turn my thumbnail into a clickable link while having the title positioned to the right?

Is there a way to create a thumbnail that acts as a link and position the title next to the thumbnail? I have experimented with using 'after' and modifying the HTML structure to align them horizontally. Any ideas on how I can achieve this layou ...

JQuery Anchor Link Scrolling Problem on Specific Devices

I'm having an issue where my webpage does not scroll correctly to an anchor when a link is clicked. The problem arises from the header size changing based on the viewport width. While it works fine in desktop Chrome, in the mobile version the header h ...

Tips for making a decision between two different functions

Below are two different pieces of jQuery code labeled as (1) and (2). I am wondering which one is more efficient and why. Additionally, should the function myfunction be placed at the top or bottom of the code? I have noticed both approaches being used in ...

Implementing a JavaScript validator for an ASP textbox

I have come across many posts discussing how to prevent an ASP textbox from accepting only numbers. However, I am looking for a JavaScript example that can check if the entered value falls between 0 and 100. My validator currently checks if each key entere ...

What is the procedure for updating a state property's value?

Currently, I am in the process of developing a small application that has the ability to fetch data, display it in the DOM, and allow users to select an item to view detailed information about the chosen user. To manage all these functionalities, I am util ...

Layers in leaflet not displaying styles

Having trouble styling the layers received from a server. I've tried using the layer.setStyle() function and defining the style when creating the layer, but nothing seems to work. Here's how my code looks: var stateStyle = { "color": "#3D522 ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...