Skip to content

filterAsync

The async counterpart to Array.prototype.filter: runs predicate for every item and resolves to the items whose predicate was truthy, in their original relative order.

predicate runs for every item up front (respecting concurrency) before any filtering happens — unlike the sync .filter(), there’s no short-circuiting, since every predicate call may already be in flight by the time an earlier one resolves.

Available since v3.0.4

import { filterAsync } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { filterAsync } from 'helpers4/array';
filterAsync<T>(array: readonly T[], predicate: function, concurrency?: number): Promise<T[]>
ParameterTypeDescription
arrayreadonly T[]The array to filter
predicatefunctionAsync (or sync) predicate called with `(item, index)`
concurrencynumberMaximum number of concurrent predicate calls. Defaults to unlimited. (optional)

Promise<T[]> — The items whose predicate resolved truthy, in original order

Keep only the files that pass an async check

Section titled “Keep only the files that pass an async check”

Every predicate call runs concurrently; matches keep their original order.

await filterAsync(files, (file) => fileExists(file))
// => only the files that actually exist

View source on GitHub