Advertisement
mikelee1111

async for each

Jan 4th, 2018 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function asyncForEach(array, callback) {
  2.     for (let index = 0; index < array.length; index++) {
  3.         await callback(array[index], index, array);
  4.     }
  5. }
  6.  
  7. async function asyncForEachByFour(array, callback) {
  8.     for (let index = 0; index < array.length; index += 4) {
  9.         const asyncArr = [];
  10.         for (let j = index; j < index + 4 && j < array.length; j++) {
  11.             asyncArr.push(callback(array[j], j, array))
  12.         }
  13.         await Promise.all(asyncArr);
  14.     }
  15. }
  16.  
  17. async function asyncQueues(
  18.     array: string[],
  19.     callback: (address: string) => Promise<void>,
  20.     numQueues: number,
  21. ) {
  22.     const queues: Record<string, string[]> = {}
  23.  
  24.     for (let index = 0; index < array.length; index += numQueues) {
  25.         for (let j = 0; j < numQueues && j + index < array.length; j++) {
  26.             queues[j] = queues[j] || []
  27.             queues[j].push(array[j + index])
  28.         }
  29.     }
  30.  
  31.     await Promise.all(Object.values(queues).map(async arr => {
  32.         for (const a of arr) {
  33.             await callback(a)
  34.         }
  35.     }))
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement