limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once.

const main = async () => {
    
    items.forEach(async (i: Item) => {
        const response = await fetch(/* code and stuff */)
    });
}

main()

The multiple requests sent to the server concurrently are causing it to get flooded with requests. Is there a way to modify the code so that the fetch calls are executed synchronously, sending only one request at a time to the URL defined in the fetch() function?

Answer №1

To properly handle multiple items, make sure to loop through them using a for loop and use await for each fetch call before moving on to the next one.

const main = async () => {
    
    for (let item of items) {
      await fetch("url with item")
    }
}

main()

If you're looking to process multiple items in chunks, take a look at this insightful article I wrote some time ago.

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

AngularJS ng-repeat items do not properly align when utilizing Bootstrap col-md-2 styles

Utilizing AngularJS ng-repeat for displaying a list of products and incorporating bootstrap col-md-2 to showcase 6 products in each row, I have included a condensed version of my code below: <!DOCTYPE html> <html lang="en"> <head> <ti ...

Restricting number input value in Vue using TypeScript

I have a component that looks like this: <input class="number-input py-1 primary--text font-weight-regular" :ref="'number-input-' + title" @keypress="onKeyPressed" :disabled="disabled& ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Struggling to configure an input field using ExtJS

I am trying to use an onChange event to update an input field with the selected option. Below is my code: HTML: <select id="builds" onchange="setBuild()"> <option value="select">Select</option> ... </select> <input ty ...

Finding the root directory of a Node project when using a globally installed Node package

I've developed a tool that automatically generates source code files for projects in the current working directory. I want to install this tool globally using npm -g mypackage and store its configuration in a .config.json file within each project&apos ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...

Error: The parameter "callback" must be in the form of a function

Following a tutorial to upload images to Twitter using Node.js with Twit. Here is the code: function upload_random_image(){ console.log('Opening an image...'); var image_path = path.join(__dirname, '/random_cam/' + random_cam()), ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

What are the recommended margins for various alphabets?

When displaying text, some alphabets take up more space than others. So how can I adjust the white space between elements '#re1' and '#re2' automatically in the scenario described below? In this code snippet, what is the best way to ad ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Javascript experiencing issues with Heapsort

I have been working on implementing heapsort in JavaScript, but I've encountered an issue with an undefined element at position array.length - 2, and the element at index 0 is not sorted. Here is the code snippet: var heapSort = function(array) { ...

Exploring the concept of nested arrays in Angular 2 using Typescript

I'm exploring the possibility of defining an array in Angular 2 that contains multiple other arrays within it. To clarify, here's what I had initially: export class PaymentDetails { account: any[]; bpNumber: number; } The issue with t ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Navigating through various product categories in Angular's routing system

Greetings! I am currently building a Shop Page in Angular 4 and encountering an obstacle with Angular routing. The issue arises when a user clicks on a product category, the intention is for the website to direct them to the shop page. On the homepage, th ...

Concealing certain options in a dropdown list with jQuery Chosen

My app has a unique feature where it displays different dropdown lists based on previous selections. Specifically, I have two lists - one for vehicle Makes and the other for Models. When a specific Make is chosen, like BMW or Audi, the next list will only ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

The element.find() function in Angular struggles to locate input elements nested within other elements

I have been working on a directive that has the following template (simplified): <table> <tr> <td> <input type="text"/> </td> <td> <inpu ...