Created
September 28, 2019 03:04
-
-
Save aada/b57e58894b1ff87d8e9c582246a75ec2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // | |
| 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