In my React application I have an array of parameters (some IDs, for example), which should be used as a parameters for an ajax call queue. The problem is that array might contain more than 1000 items and if I just recursively make the ajax call using the forEach loop, the browser page eventually stops responding before each of the requests are resolved.
Is there a technique/library, which could allow to send ajax requests, for example, by 5 requests at a time asynchronously, and only when those are finished, proceed the next 5?
Follow up questions:
if you are not constrained by es version and can use es6 then you should look into async await
async/await is meant for the exact scenario of awaiting async calls. basically inside the async function until await is resolved the execution is suspended. You would need to understand promises and generators before you start using them.
Ok, let's sort some things out. In JavaScript AJAX requests are asynchronous by nature. You chose to make them synchronous somewhat in you implementation.
What you need to do is have some array of requests, from which you pop results X at a time, wait for them to return, and repeat.
Will execute 5 requests simultaneously, wait for them to complete, then fetch next portion of IDs
In these sort of cases, it is best to change in backend where you can process results for thousand inputs send them at one instead of calling from a thousand times. Another way is to use promise I think.
You can also look at this link if it is applicable for you. I think these things answer your question
I had the same problem in a project. What you need is a priority queue in order to control how many request will be performed simultaneously. I'm using this library. Since the p-queue implementation is simple enough to understand and is not that big, I've pasted the code in the snippet below only to show you how it works in the latest lines.