Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization after all requests are complete to execute additional code.

I have explored various suggestions from:

Limit number of requests at a time with RxJS

How to limit the concurrency of flatMap?

Fire async request in parallel but get result in order using rxjs

and more... I even attempted to create my own operators.

However, either the solutions provided do not align with my specific requirements or I am struggling to integrate them seamlessly into my existing codebase.

This is the current state of my implementation:

for (const obj of objects) {
  this.myService.updateObject(obj).subscribe(value => {
    this.anotherService.set(obj);
  });
}

EDIT 1: I believe progress is being made! Utilizing the insights from Julius and pschild, I have managed to control the request concurrency. However, only the first batch of 4 requests is triggered while subsequent batches remain inactive. Here's the updated snippet:

const concurrentRequests = 4;
from(objects)
  .pipe(
    mergeMap(obj => this.myService.updateObject(obj), concurrentRequests),
    tap(result => this.anotherService.set(result))
  ).subscribe();

Is there an issue with the way I'm handling the subscribe() method?

By the way: The use of mergeMap with the resultSelector parameter has been deprecated, hence why I omitted it. Also, the reference to obj within the mergeMap function is not accessible in the tap, necessitating the use of the parameter passed to tap.

EDIT 2:

Ensure that your observers complete! (This lesson cost me an entire day)

Answer №1

If you want to restrict the number of simultaneous inner subscriptions, you can utilize the third parameter of mergeMap. Additionally, you can make use of finalize to run a task after all requests have been completed:

const maxConcurrentRequests = 5;
from(objects)
    .pipe(
        mergeMap(obj => this.myService.updateObject(obj), maxConcurrentRequests),
        tap(res => this.anotherService.set(res))),
        finalize(() => console.log('Sequence complete'))
    );

Check out the demonstration on Stackblitz.

Answer №2

Using the objects array, this code snippet filters them into batches of 10 and then performs an asynchronous update operation on each object using myService. After updating each object, it also calls another service method to set additional values. Finally, it logs a message indicating that all requests have been completed.

This code is provided as an example and has not been tested. Feel free to ask for clarification or report any errors.

Answer №3

I encountered a similar problem in the past while attempting to load multiple images from a server. To address this issue, I had to send HTTP requests sequentially, ultimately achieving my desired outcome by utilizing awaited promises. Below is a snippet of the code I used:

async ngOnInit() {
    for (const number of this.numbers) {
      await new Promise(resolve => {
        this.http.get(`https://jsonplaceholder.typicode.com/todos/${number}`).subscribe(
          data => {
            this.responses.push(data);
            console.log(data);
            resolve();
          }
        );
      });
    }
  }

The key concept here is to resolve the promise upon receiving the response. This approach allows for the implementation of custom logic to execute certain actions once all requests have been completed.

You can view the live demo on StackBlitz. Make sure to check the console for real-time updates! :)

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

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

Angular component fails to render when passed as a string in the innerHtml attribute

One interesting challenge I faced is working with an API that returns HTML containing Angular components which are not being displayed in the application. I am trying to figure out how to display an Angular component stored as a string within the HTML con ...

What is the evaluation process for conditions like someItem?.someField==somevalue in Angular?

Let's consider a simple condition in the markup: someItem?.someField==somevalue What does this mean? Is it equivalent to someItem!=null && someItem!=undefined && someItem==somevalue So essentially, if someItem is undefined, the ent ...

The Print Preview Displays No Content When an External Stylesheet Reference is Included in the Printable HTML Content

Is there a way to print the contents of a DIV on a webpage? Currently, I am using JavaScript to retrieve the contents of the div and then passing it to a new window object where I call the .print() function. The text contents and images are displayed corre ...

Troubleshooting: ng-disabled not function properly in Angular.js

My goal is to only allow the button to be enabled if there is text in the textfield, but for some reason I am unable to make ng-disabled work: <form novalidate> <button type="submit" ng-click="add('+')" ng-disabled="bittext.$invalid ...

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

Encounter the following issue: Unable to access property '0' due to being undefined

After restructuring my entire Javascript code, I managed to solve the problem with asynchronous calls. However, an error occurs when editing a repair and the server prompts the client for repair information again. The error message displayed is "Uncaught ...

develop the following application and execute the npm run dev command, but encounter the error message: "Command failed with exit code 1."

After executing npx create-next-app@latest followed by npm run dev, I encountered the error message Command failed with exit code 1.. Additionally, when trying to access https://localhost:3000, an error stating ERR_CONNECTION_REFUSED was displayed. Further ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

The css property of *ngContainerOutlet is ineffective when applied to an ng-component with encapsulation

When I utilize *ngContainerOutlet to dynamically insert components, it wraps the component's template within an ng-component tag which causes my CSS styles to become ineffective. For example: <div class="my-class"> <ng-container *ngComp ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

The type 'typeof globalThis' does not have an index signature, therefore the element is implicitly of type 'any'. Error code: ts(7017) in TypeScript

I'm encountering an issue with my input handleChange function. Specifically, I am receiving the following error message: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when att ...

Developing a JavaScript library that utilizes flow type annotations and provides access to various data types

I am currently developing a library intended for use by third parties. I have opted to utilize flowtype as the typing system for specific reasons within my organization. This library presents React components with annotations. The library itself is annota ...

Using the `import.meta` meta-property is restricted to the `es2020`, `esnext`, or `system` options in snowpack+testing-library and will result in an error

I've been encountering issues while setting up Jest and React Testing Library for the snowpack project. The error message I'm receiving is "The 'import.meta' meta-property is only allowed when the '--module' option is 'es ...

What is the method for utilizing a function's input type specified as "typeof A" to output the type "A"?

Check out this example from my sandbox: class A { doSomething() {} } class B {} const collection = { a: new A(), b: new B() } const findInstance = <T>(list: any, nonInstance: T): T => { for (const item in list) { if (lis ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...