Documentation
    Preparing search index...

    Function asyncMap

    • Transforms each element of an array using an asynchronous function to create a new array.

      Similar to JavaScript's native map but processes asynchronous functions sequentially. Each element's transformation is completed before proceeding to the next element, ensuring order is maintained.

      Processing cost: Each of N elements invokes its mapper once in sequence and stores one result: O(N) bookkeeping and output space.

      Resource ownership: The invocation awaits one callback at a time and retains only its partial output and current call; success transfers the output to the caller and rejection releases local state. Callback-owned external resources remain the callback owner’s responsibility.

      Type Parameters

      • Input

        The type of elements in the input array

      • Output

        The type of elements in the resulting array

      Parameters

      • elements: readonly Input[]

        The readonly array to transform

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

        The asynchronous function that transforms each element

      Returns Promise<Output[]>

      A Promise resolving to the transformed array

      const userIds = [1, 2, 3, 4, 5];

      const userDetails = await ArrayUtil.asyncMap(
      userIds,
      async (id, index) => {
      console.log(
      `Fetching user ${id} (${index + 1}/${userIds.length})`,
      );
      const response = await fetch(`/api/users/${id}`);
      return await response.json();
      },
      );
      console.log("All users fetched:", userDetails);

      contracts/common.md#principled-implementation The closure result of each element is pushed in iteration order, so the output order equals the input order, which holds because the calls are sequential.

      contracts/common.md#clear-and-simple-design It composes asyncForEach with one push.

      contracts/common.md#prohibited-implementation-shortcuts Every element is transformed by the caller's closure, with no memoization or skipping.

      contracts/common.md#meaningful-documentation The comment states the sequential order and the parameters, and the example calls the two-argument form the function has.