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.

  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');
  • Type Parameters

    • Input

      The type of elements in the input array

    Parameters

    • elements: readonly Input[]

      The readonly array to process

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

    A function that takes an async closure and returns a Promise