Skip to content

Instantly share code, notes, and snippets.

@eatoncw
Created August 18, 2020 20:17
Show Gist options
  • Save eatoncw/040b336d440fc3716db1af41d7050671 to your computer and use it in GitHub Desktop.
Save eatoncw/040b336d440fc3716db1af41d7050671 to your computer and use it in GitHub Desktop.
batch async
// 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