Tips for effectively running multiple XMLHttpRequests in a loop

While running XMLHttpRequest inside .map(), everything operates smoothly.

   list.map(function(file) {
     const xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function () {}
     xhr.onerror = function () {}
     xhr.upload.addEventListener('progress', (e) => {}
     xhr.send(file);
   }

The issue lies in the fact that this loop initiates all xhr.send() calls at the same time.
What measures should I take to ensure these iterations happen sequentially?
How can I make sure one request completes before the next one starts?

Answer №1

In the realm of asynchronous programming, one question has stood the test of time, compelling developers to explore a multitude of innovative solutions.

Currently, functional programming is all the rage, offering a range of clever techniques. Let me unveil a few tricks that enable you to sequence any collection of asynchronous tasks for sequential execution.

To begin with, opt for using fetch() over XMLHttpRequest. Then, harness methods such as apply, compose, and thunking in the following manner:

const urls = ['https://www.example.com', 'https://blog.sample.org'];

let progress = 0;

const fetchHtml = url => {
  return fetch(url).then(resp => resp.text());
};

const updateProgressbar = (html) => {
  console.log('Updating progress bar!');
  return ++progress/urls.length;
};

const thunk = (f, ...args) => () => f(...args);
const apply = (acc,val) => acc.then(val);
const compose = (...funcs) => x => funcs.reduce(apply, Promise.resolve(x));
const sequence = (f, inputs) => compose(...inputs.map(input => thunk(f, input)))();

sequence(compose(fetchHtml, updateProgressbar, console.log), urls);

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 the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

Express Session doesn't remove the variable assigned

While developing a web application using Node Express, I encountered a simple issue in my new project. Despite setting a session variable to null, the old session data is still being called. Seeking assistance to resolve this issue. I utilized express-ses ...

Sending a variable from the server to the client using express rendering in Node.js

When using a Node.js express server, I am attempting to pass a variable to the index.ejs file on the client side. In my server code, I have added: res.render("dashboard/index", { hidePayment: true }); The problem arises when trying to access the hidePayme ...

Executing JavaScript code within a class object using ASP-VB

I'm looking to create a function that will show a Javascript-based notification. I already have the code for the notification, but I'm trying to encapsulate it in a class library as a function. However, I am unsure about what to return from the f ...

Is it possible to send an ajax request to a user control file with the extension .ascx?

I am trying to interact with a user control on my page through ajax. Is it possible to make an ajax request directly to the user control (.ascx) instead of .aspx or .ashx files? ...

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

Limiting the quantity in SimpleCart (js)

Currently, I am working on a WordPress website where I am using simpleCart(js) to add a shopping cart feature. I sell unique articles and do not require users to add more than one article to their cart. My main concern is how to prevent users from adding ...

Display the contents of a <div> tag from one HTML file onto another HTML file

Recently I embarked on learning HTML and came across a peculiar doubt. My goal is to create a section div on the first page that changes dynamically based on the menu item clicked, rather than redirecting to another HTML page. I've experimented with s ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

NodeJS encountered a SyntaxError while trying to export the 'routes' object as

const paths = (app) => { app.route('/contact') .get((req, res, next) => { // middleware console.log(`Request from: ${req.originalUrl}`) console.log(`Request type: ${req.method}`) next(); }, (req, res, next) = ...

mention a numerical value/heading within a JSON list

I encountered an issue while searching through a JSON array filled with Google fonts. The fonts are structured by family -> files -> filename. However, I noticed that sometimes the filename is saved as a number. For example (refer to the bottom of th ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code: var userId = req.params.UserId const m ...

Adding a clickable button to execute code within a LeafletJS marker!

I'm currently experimenting with adding a button inside a pointer that will log a message to the console. This is simply a test to see if I can execute a method on the marker, but so far I haven't been able to display any text. const marker = L.m ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Once data has been received using @requestbody, I aim to either send a message or initiate a webpage redirection

Controller: @RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json") @ResponseBody public RegInfo receiveData(@RequestBody RegInfo info){ String reg_check = regInfoService.checkRegInfo(info); ...... } RegIn ...

Assign the physics settings to a variable within the A-frame

Exploring A-frame () for my scene creation has been exciting. I am curious about how I can dynamically adjust the physics in my virtual world using the A-frame physics component. The goal is to have the physics within my scene be determined by a variable c ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple example ...

Tips for organizing Protractor promises

I am currently experimenting with determining if an element is positioned at the bottom of a page in Protractor/Webdriver using promises. However, I feel like my current approach is quite messy and there must be a cleaner way to achieve this. describe(&ap ...