Home > front end >  How to automate taking X amount of items from array in a loop request
How to automate taking X amount of items from array in a loop request

Time:10-19

I have a large array filled with id's (array size will always be large, over 1000 for example) like this [000001,000002,000003,000004,...] and I want to send a request to an API that can contain up to 100 of these id's at a time (this is a limit, only 100 id's per request and out of my control)

The endpoint takes these id's as url params like so ?ids=000001,000002,000003,000004,... but I am struggling to figure out the logic I would need to perform to loop through every 100 entries and take those entries, send the request and then repeat until all entries have been added to a request?

This is my first question here on SO so apologies if this isn't quite the correct format, I just really need a logic check on this one...

CodePudding user response:

You can use JSON like this :

let createdJson = JSON.stringify(myIntArray);
// here send your request with :
sendRequest("http://url/?json="   createdJson);

Then, in the other side you use something like :

In this example, I'm using PhP.

$intArray = json_decode($_GET["json"]);
// now you have your int array

CodePudding user response:

The general principle would be to split your large array into chunks first, then form a request from each chunk, send it, wait for the reponse, keep hold of the results and then send the next.

Here's some code with no details:

const chunks = chunkArray(largeArray) // returns an array of arrays
let responses = []
for(const chunk of chunks){
    const query = createQueryStringFromArray(chunk)
    const response = await sendQuery(query) // post to API
    responses = [...responses, response] // keep hold of results
}
  • Related