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

    Function asyncFilter

    • Asynchronously filters an array based on an asynchronous predicate function. Only elements for which the predicate returns true are included in the result.

      The function allows limiting the number of concurrently executed predicates, making it useful for managing concurrency in asynchronous operations (e.g., API checks, database queries).

      Type Parameters

      • T

        The type of elements in the input array

      Parameters

      • array: T[]

        The array of elements to filter.

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

        The asynchronous predicate function that will be executed for each element. Should return true to include the element, false to exclude it.

      • Optionaloptions: { concurrency?: number; continueOnError?: boolean } = {}

        Optional configuration

        • Optionalconcurrency?: number

          Maximum number of concurrent operations

        • OptionalcontinueOnError?: boolean

          Whether to continue filtering when a predicate throws. When true, elements that throw errors are excluded from the result.

      Returns Promise<T[]>

      A Promise that resolves to the filtered array.

      // Basic usage
      const numbers = [1, 2, 3, 4, 5];
      const evens = await asyncFilter(numbers, async (n) => n % 2 === 0);
      // Result: [2, 4]
      // With API validation
      const userIds = [1, 2, 3, 4, 5];
      const activeUsers = await asyncFilter(userIds, async (id) => {
      const user = await api.getUser(id);
      return user.status === 'active';
      });
      // With limited concurrency
      const items = [...Array(100).keys()];
      const validated = await asyncFilter(items, validateItem, { concurrency: 5 });
      // Only 5 validation calls will run at a time
      // With error handling
      const urls = ['url1', 'url2', 'url3'];
      const reachable = await asyncFilter(urls, async (url) => {
      const response = await fetch(url);
      return response.ok;
      }, { continueOnError: true });
      // If fetch fails for any URL, that URL is excluded from results