Skip to content

Instantly share code, notes, and snippets.

@maartenbusstra
Last active April 14, 2019 02:44
Show Gist options
  • Save maartenbusstra/6762d3636c33a79f8bed0cb0339ef7ba to your computer and use it in GitHub Desktop.
Save maartenbusstra/6762d3636c33a79f8bed0cb0339ef7ba to your computer and use it in GitHub Desktop.
Perform async map in batches
const batchedMap = batchSize => data => async (fn) => {
const batches = data.length / batchSize;
let result = [];
for (let i = 0; i < batches; i++) {
const res = await Promise.all(data
.slice(i * batchSize, (i + 1) * batchSize)
.map((d, j) => fn(d, (i * batchSize) + j)),
);
result = result.concat(res);
}
return result;
};
// usage
await batchedMap(batchSize)(data)((item, index) => somethingAsync(item, index));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment