TS-Scribe - v1.2.0
    Preparing search index...

    Function asyncForEach

    • Asynchronously iterates over an array, executing a provided callback function for each element. Rejects on the first error.

      For collecting errors instead of failing fast, use asyncForEachSettled.

      Type Parameters

      • T

        The type of elements in the input array

      Parameters

      • array: T[]

        The array of elements to iterate over.

      • callback: (element: T, index: number, array: T[]) => Promise<void>

        The asynchronous callback function that will be executed for each element.

      • Optionaloptions: { concurrency?: number; signal?: AbortSignal } = {}

        Optional configuration

        • Optionalconcurrency?: number

          Maximum number of concurrent operations

        • Optionalsignal?: AbortSignal

          AbortSignal to cancel processing.

      Returns Promise<void>

      A Promise that resolves when all elements have been processed.

      If concurrency is not a positive integer.

      If the input array is null or undefined.

      If the signal is aborted.

      The first error thrown by the callback.

      // Basic usage
      await asyncForEach([1, 2, 3, 4], async (number) => {
      await delay(500);
      console.log(number);
      });
      // With limited concurrency
      const urls = ['url1', 'url2', 'url3', 'url4', 'url5'];
      await asyncForEach(urls, fetchAndSave, { concurrency: 2 });
      // With AbortSignal
      const controller = new AbortController();
      setTimeout(() => controller.abort(), 5000);
      await asyncForEach(items, processItem, { signal: controller.signal });