Last active
April 14, 2019 02:44
-
-
Save maartenbusstra/6762d3636c33a79f8bed0cb0339ef7ba to your computer and use it in GitHub Desktop.
Perform async map in batches
This file contains 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 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