Skip to content

Instantly share code, notes, and snippets.

@hartzis
Last active March 3, 2022 00:42
Show Gist options
  • Save hartzis/ab7b10132ac09cdb63e10d376e10a199 to your computer and use it in GitHub Desktop.
Save hartzis/ab7b10132ac09cdb63e10d376e10a199 to your computer and use it in GitHub Desktop.
batch and throttle async requests node/js
const MAX_BATCH_SIZE = 10;
const WAIT_TIME_MS = 1000;
const makeRequest = async (id) => {
try {
await fetch(`/api/${id}`)
} catch(error) { }
}
const batchesOfIds = _.chunk(Ids, MAX_BATCH_SIZE);
for (const chunkOfIds of batchesOfIds) {
// Setup throttle before starting requests,
// since all requests could finish before throttle ends
const throttleBatches = new Promise((resolve) => setTimeout(resolve, wait));
const requests = chunkOfStoreIds.map(makeRequest);
// make sure batch "finishes" before moving on
await Promise.all(requests);
// wait the minimum time between batches of requests
await throttleBatches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment