Skip to content

Async Find

Sykander edited this page Feb 25, 2020 · 11 revisions

The asyncFind() method returns the value of the first element in the provided iterable object that satisfies the provided testing function.

Syntax

asyncArr.asyncFind(callback(currentValue[, index[, array]])[, 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

The value of the first element in the iterable object that satisfies the provided testing function. Otherwise, undefined is returned.

Description

The asyncFind method executes the callback function once for each index of the iterable object until the callback returns a truthy value. If so, asyncFind immediately returns the value of that element. Otherwise, find returns undefined.

callback is invoked for every index of the iterable object, not just those with assigned values. This means it may be less efficient for sparse arrays, compared to methods that only visit assigned values.

The asyncFind method does not mutate the iterable object on which it is called, but the function provided to callback can. If so, the elements processed by asyncFind are set before the first invocation of callback. Therefore:

  • callback will not visit any elements added to the iterable object after the call to asyncFind begins.
  • If an existing, yet-unvisited element of the iterable object is changed by callback, its value passed to the callback will be the value at the time asyncFind visits that element's index.
  • Elements that are deleted are still 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

Finding first large item

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

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

console.log('Resolved Element ', found);
Resolved Element 3
Clone this wiki locally