Skip to content

Instantly share code, notes, and snippets.

@aada
Created September 28, 2019 03:04
Show Gist options
  • Select an option

  • Save aada/b57e58894b1ff87d8e9c582246a75ec2 to your computer and use it in GitHub Desktop.

Select an option

Save aada/b57e58894b1ff87d8e9c582246a75ec2 to your computer and use it in GitHub Desktop.
//
export async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
export function split(arr, n) {
var res = [];
while (arr.length) {
res.push(arr.splice(0, n));
}
return res;
}
export const delayMS = (t = 200) => {
return new Promise(resolve => {
setTimeout(() => {
resolve(t);
}, t);
});
};
export const throttledPromises = (
asyncFunction: (any) => Promise<any>,
items = [],
batchSize = 1,
delay = 0
) => {
return new Promise(async (resolve, reject) => {
const output = [];
const batches: any[] = split(items, batchSize);
await asyncForEach(batches, async (batch: any[]) => {
const promises = batch.map(asyncFunction).map(p => p.catch(reject));
const results = await Promise.all(promises);
output.push(...results);
await delayMS(delay);
});
resolve(output);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment