Skip to content

Async Filter

Sykander edited this page Jul 11, 2020 · 18 revisions

The asyncFilter() method creates a new array with all elements that pass the test implemented by the provided async function.

Syntax

let newArray = await asyncArray.asyncFilter(
    async function callback(currentValue[, index[, array]]) {
        // test currentValue to pass filter
    }
    [, thisArg]
);

Parameters

  • callback Async function to execute on each element. It accepts between one and three arguments:
    • currentValue The current element being processed in the iterable object.
    • index |optional The index of currentValue in the iterable object.
    • array |optional The iterable object that asyncFilter was called upon.
  • thisArg optional Value to use as this when executing callback.

Return Value

A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.

Description

asyncFilter() calls a provided callback function, which can be async, once for each element in an iterable object, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the iterable object which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Iterable object elements which do not pass the callback test are simply skipped, and are not included in the new array.

callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the iterable object being traversed

If a thisArg parameter is provided to asyncFilter, it will be used as the callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

asyncFilter does not mutate the iterable object on which it was called.

The range of elements processed by asyncFilter() is set before the first invocation of callback. Elements which are appended to the iterable object after the call to asyncFilter() begins will not be visited by callback. If existing elements of the iterable object are changed, or deleted, their value as passed to callback will be the value at the time asyncFilter() visits them; elements that are deleted are not visited.

Errors

TypeError

Type Error will be thrown if the callback is not a function or if the method is bound on an object which isn't iterable.

Examples

Filtering out small entries

const { AsyncArray } = require('iterable-async'),
  asyncArray = AsyncArray.from([1, 2, 3, 4, 5]);

const found = await asyncArray.asyncFilter(async element => {
    return element > 2;
});

console.log('Resolved Array ', ...found);
Resolved Array 3, 4, 5
Clone this wiki locally