In my react application, I have a Grid. User can select many grid rows at a time and click on a button to take bulk action on selected grid rows.
On a server side I have a script which I want to execute for each selected row (to make question simple I am making call to "jsonplaceholder.typicode.com" in the example below for each selected row) on a click of a bulk action button. On bulk action button click, I get selectedRows in action creator, where I iterate over selectedRows and make ajax call for each of the selected row.
Since selectedRows may contain more than 1000 items and if I just iteratively make the ajax call using the forEach loop, the browser page may eventually stop responding before each of the requests are resolved. Hence I used solution below, to send request in a batch of 5 and then wait until those 5 are resolved.
// Action creator, selectedRows is an array.
function onGridRowsSelection(selectedRows) {
makeBatchCalls(selectedRows,5)
}
async function makeBatchCalls(selectedRows, length) {
let test = arrayIds.reduce((rows, key, index) => (index % length == 0
? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
let Batchresults = []; //convert them to two dimensionl arrays of given length [[1,2,3,4,5], [6,7,8,9,10]]
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
}
Solution above works fine, but has one problem,
- Select more than 5 rows from a grid and click on bulk action button,
- Again select more than 5 rows and click on bulk action button,
- Now I see 10 requests active at a time.
How can I restrict this?
Follow up question for the problem mentioned here is asked in React - controlling async calls smartly without any side effect in complex applications
This question is a follow up question of JavaScript, React - sending multiple simultaneous ajax calls