The type of elements in the input array
A Promise resolving to the filtered array
const users = [
{ id: 1, name: "Alice", active: true },
{ id: 2, name: "Bob", active: false },
{ id: 3, name: "Charlie", active: true },
];
const activeUsers = await ArrayUtil.asyncFilter(
users,
async (user) => {
// Async validation logic (e.g., API call)
await new Promise((resolve) => setTimeout(resolve, 100));
return user.active;
},
);
console.log(activeUsers); // [{ id: 1, name: 'Alice', active: true }, { id: 3, name: 'Charlie', active: true }]
contracts/common.md#principled-implementation The predicate runs on each element in order and the next call starts after the previous promise settles; an element is kept only when the awaited result is exactly true, which the Promise<boolean> type guarantees for well-typed callers, and a rejection stops the iteration and rejects the result.
contracts/common.md#clear-and-simple-design It composes asyncForEach with one push instead of reimplementing the loop.
Filters an array by applying an asynchronous predicate function to each element.
Elements are processed sequentially, ensuring order is maintained. The predicate function receives the element, index, and the full array as parameters.
Processing cost: Each of N elements invokes its predicate once in sequence; array bookkeeping is O(N), with O(M) output for M accepted elements.
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.