TS-Scribe - v0.6.2
    Preparing search index...

    Function asyncForEach

    • Asynchronously iterates over an array, executing a provided callback function for each element. The function allows limiting the number of concurrently executed tasks, making it useful for managing concurrency in asynchronous operations (e.g., network requests, file operations).

      The function waits for all asynchronous operations to complete before resolving.

      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; continueOnError?: boolean } = {}

        Optional configuration

        • Optionalconcurrency?: number

          Maximum number of concurrent operations

        • OptionalcontinueOnError?: boolean

          Whether to continue iterating when a callback throws

      Returns Promise<void>

      A Promise that resolves when all elements have been processed.

      // 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 });
      // Only 2 requests will run at a time
      // With error handling
      await asyncForEach(ids, processItem, {
      continueOnError: true,
      });
      // If processItem throws for any id, iteration continues for the remaining items