Created
August 18, 2020 20:17
-
-
Save eatoncw/040b336d440fc3716db1af41d7050671 to your computer and use it in GitHub Desktop.
batch async
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
// takes a large array of items, chunks them, performs an async task on that item | |
import { chunk } from "lodash"; | |
function wait(time: number) { // in ms | |
return new Promise(resolve => setTimeout(resolve, time)); | |
} | |
export async function batch( | |
arr: any, | |
size: number, | |
task: function, | |
delay: number = 1000 | |
) { | |
const chunks = chunk(arr, size); | |
return chunks.reduce(async (previousPromise, nextChunk) => { | |
await previousPromise; | |
await wait(delay); | |
return task(nextChunk); | |
}, Promise.resolve()); | |
} | |
// eg | |
let allOfSomething = await getAll(); | |
function deleteSomething(group: any) { | |
return Promise.all( | |
group.map((item: any) => { | |
return item.delete(); | |
}) | |
); | |
} | |
await batch(allOfSomething, 250, deleteSomething); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment