Skip to content

Instantly share code, notes, and snippets.

@lionelB
Created August 13, 2020 09:58
Show Gist options
  • Save lionelB/4b295e50e6d449221080e81b6ce393c7 to your computer and use it in GitHub Desktop.
Save lionelB/4b295e50e6d449221080e81b6ce393c7 to your computer and use it in GitHub Desktop.
function range(start, end, size = 1) {
return Array.from(
{ length: Math.ceil((end - start) / size) },
(_, i) => start + i * size
);
}
function batch(items, size) {
return range(0, items.length, size).map(val => {
return items.slice(val, val + size);
});
}
export async function batchPromise(list, size, callback) {
let results = [];
let nbBatch = 0;
for (const items of batch(list, size)) {
const values = await Promise.all(
items.map((item, i) => callback(item, i + nbBatch * size, list))
);
nbBatch += 1;
results = [...results, ...values];
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment