Last active
March 3, 2022 00:42
-
-
Save hartzis/ab7b10132ac09cdb63e10d376e10a199 to your computer and use it in GitHub Desktop.
batch and throttle async requests node/js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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