promise.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Divide arrays into batches, and apply a given function to each batch by using Promise.all
  3. * Use when memory consumption can be too large by using simple Promise.all
  4. * @param items array to process
  5. * @param limit batch size
  6. * @param fn function to apply on each item
  7. * @param throwIfRejected whether or not to throw Error when there is a rejected Promise
  8. * @returns result of fn applied to each item
  9. */
  10. export const batchProcessPromiseAll = async <I, O>(
  11. items: Array<I>,
  12. limit: number,
  13. fn: (item: I, index?: number, array?: Array<I>) => Promise<O>,
  14. throwIfRejected = true,
  15. ): Promise<O[]> => {
  16. const results: O[] = [];
  17. for (let start = 0; start < items.length; start += limit) {
  18. const end = Math.min(start + limit, items.length);
  19. // biome-ignore lint/performance/noAwaitInLoops: Allow for memory consumption control
  20. const slicedResults = await Promise.allSettled(
  21. items.slice(start, end).map(fn),
  22. );
  23. slicedResults.forEach((result) => {
  24. if (result.status === 'fulfilled') {
  25. results.push(result.value);
  26. } else if (throwIfRejected && result.reason instanceof Error) {
  27. throw result.reason;
  28. }
  29. });
  30. }
  31. return results;
  32. };