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 library, which could allow to send ajax requests, for example, maintaining 5 requests at a time asynchronously.
This is the code which I am using for now.
async function makeBatchCalls(arrayIds, length)
{
//convert arrayIds to two dimensional arrays of given length [[1,2,3,4,5], [6,7,8,9,10] ....]
let test = arrayIds.reduce(
(rows, key, index) => (index % length == 0
? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
let Batchresults = [];
for (calls of test) {
Batchresults.push(await Promise.all(calls.map((call)=>fetch(`https://jsonplaceholder.typicode.com/posts/${call}`))));
}
return Promise.all(Batchresults); //wait for all batch calls to finish
}
makeBatchCalls([1,2,3,4,5,6,7,8,9,10,12,12,13,14,15,16,17,18,19,20],5)
Problem with this code is it waits for 5 calls to complete and then send another batch of 5 calls. This is not an effective utilisation of the network. What I want is at any point of time there should be 5 requests.
Is it possible to tweak above code itself to cater the requirements?