I have an array of objects, and for each object inside the array I want to call an asynchronous function.
However, I should only send 20 requests in a minute.
Example:
const myArray = ["a","b","aa","c","fd","w"...]
myArray length is 60.
I used to split myArray into sub-arrays of length 20 each and iterate over each sub-array and call the async function.
Then wait for a minute and then iterate over the next sub-array and so on. However I was doing that manually in a way such as
let promise;
let allPromises = [];
// Iterate over subArray1 and call the function for each element
for(let i = 0 ; i < subArray1.length ; i++){
promise = await myAsyncFunc(subArray1[i]);
allPromises.push(promise);
}
// wait for all the async functions to get resolved using Promise.all()
await Promise.all(allPromises);
allPromises = [];
await new Promise((resolve) => setTimeout(resolve, 60000));
if(subArray2){
// Iterate over subArray2 and call the function for each element
for(let i = 0 ; i < subArray2.length ; i++){
promise = await myAsyncFunc(subArray2[i]);
allPromises.push(promise);
}
// wait for all the async functions to get resolved using Promise.all()
await Promise.all(allPromises);
allPromises = [];
await new Promise((resolve) => setTimeout(resolve, 60000));
}
if(subArray3){
// Iterate over subArray3 and call the function for each element
for(let i = 0 ; i < subArray3.length ; i++){
promise = await myAsyncFunc(subArray3[i]);
allPromises.push(promise);
}
// wait for all the async functions to get resolved using Promise.all()
await Promise.all(allPromises);
allPromises = [];
await new Promise((resolve) => setTimeout(resolve, 60000));
}
If my array got more than 100 elements that would be an issue. Can anyone provide a practical way to handle this situation?