Specify the number of simultaneous times an API call takes place

Viewed 42

I have the following object:

addresses: [
    {
        address: "1234 Main St",
        city: "San Diego",
        state: "CA",
        zip: 92014
    },
    {
        address: "4444 Main St",
        city: "San Diego",
        state: "CA",
        zip: 92014
    },
    {
        address: "5555 Main St",
        city: "San Diego",
        state: "CA",
        zip: 92014
    },
    {
        address: "6666 Main St",
        city: "San Diego",
        state: "CA",
        zip: 92014
    },
    {
        address: "7777 Main St",
        city: "San Diego",
        state: "CA",
        zip: 92014
    }
]

The real one has about 1,500 records.

This array is loaded on an angular application and displayed on a table.

For each address at this array, an API is called (on my end), where the address is verified.

The problem I have is I was asked to place a "VERIFY ALL" button, and when running the above array through a loop, it all works fine when calling the API 45-50 times, the rest of the calls just won't respond.

for (let address of addresses) {
    //here Im calling the API for each address, and getting a "True" or "False" response
}

Is it possible to run the API call (from Angular) in batches of 10 addresses, and move to the next 10 ones after those provided already a response?

Thanks.

1 Answers

You can separate them into batches like so:

  results: boolean[] = [];

  async ngOnInit() {
    const batchSize = 3;
    const numBatches = Math.ceil(addresses.length / batchSize);
    for (let batch = 0; batch < numBatches; batch++) {
      const promises = [];
      for (let i = 0; i < batchSize; i++) {
        const index = batch * batchSize + i;
        if (index >= addresses.length) break;
        const promise = firstValueFrom(this.api.callApi(addresses[index]));
        promises.push(promise);
      }
      const batchResults = await Promise.all(promises);
      for (const result of batchResults) this.results.push(result);
      // Optional sleep between batches
      const sleep = 5000;
      await new Promise((resolve) => setTimeout(() => resolve(null), sleep));
    }
    console.log(this.results);
  }

Here's an example calling the jokes api, waiting 5 seconds between so you can see each batch come in:

https://stackblitz.com/edit/angular-ivy-vvrimb?file=src/app/app.component.ts

Keep in mind that api has a limit of 120 requests every 60 seconds so you'll get errors if you refresh too fast.

Related