Documentation
    Preparing search index...

    Function asyncForEach

    • Executes an asynchronous function for each element in an array sequentially.

      Unlike JavaScript's native forEach, this function processes asynchronous functions sequentially and waits for all operations to complete. It performs sequential processing rather than parallel processing, making it suitable for operations where order matters.

      Processing cost: Each of N elements invokes its callback once in sequence: O(N) bookkeeping with no result array.

      Resource ownership: The invocation retains its input while awaiting one callback at a time, discards callback results and releases local state on completion or rejection. Callback-owned external resources remain the callback owner’s responsibility.

      Type Parameters

      • Input

        The type of elements in the input array

      Parameters

      • elements: readonly Input[]

        The readonly array to process

      • closure: (elem: Input, index: number, array: readonly Input[]) => Promise<any>

        The asynchronous function to execute for each element

      Returns Promise<void>

      A Promise that resolves when all operations complete

      const urls = ["url1", "url2", "url3"];

      await ArrayUtil.asyncForEach(urls, async (url, index) => {
      console.log(`Processing ${index}: ${url}`);
      const data = await fetch(url);
      await processData(data);
      console.log(`Completed ${index}: ${url}`);
      });
      console.log("All URLs processed sequentially");

      contracts/common.md#principled-implementation The initial array length determines the visited indices, and each callback receives the current element, index and original array. Each call is awaited before advancing, so rejection ends iteration and propagates.

      contracts/common.md#clear-and-simple-design One sequential loop discards callback results without collecting an unused array.

      contracts/common.md#prohibited-implementation-shortcuts The closure receives every element exactly once and no error is swallowed.

      contracts/common.md#meaningful-documentation The comment contrasts it with the native forEach, states the sequential semantics, and gives an example.