Skip to content

Async Find Index

Sykander edited this page Feb 24, 2020 · 6 revisions

The asyncFindIndex() method returns the index of the first element in the iterable object that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

Syntax

asyncArr.asyncFindIndex(callback(element[, index[, array]])[, thisArg])

Parameters

  • callback An async function to execute on each value in the iterable object until the function returns true, indicating that the satisfying element was found. It takes three arguments:
    • element The current element being processed in array.
    • index |Optional The index of the current element being processed in array.
    • array |Optional The iterable object asyncFindIndex was called upon.
  • thisArg |Optional Optional object to use as this when executing callback.

Return value

The index of the first element in the iterable object that passes the test. Otherwise, -1.

Description

The asyncFindIndex method executes the callback function once for every index 0..length-1`` (inclusive) in the iterable object until it finds the one where callbackreturns a *truthy* value (a value that coerces totrue`).

If such an element is found, asyncFindIndex immediately returns the element's index. If the callback never returns a truthy value (or the iterable objects's length is 0), asyncFindIndex returns -1. Unlike other array methods such as Array.some, the callback is called even for indexes with unassigned values.

callback is invoked with three arguments:

The value of the element The index of the element The Array object being traversed If a thisArg parameter is passed to findIndex, it will be used as the this inside each invocation of the callback. If it is not provided, then undefined is used.

The range of elements processed by findIndex is set before the first invocation of callback. callback will not process the elements appended to the array after the call to findIndex begins. If an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findIndex visits the 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

As a method

const { asyncFind } = require('iterable-async'),
 array = [1, 2, 3];

array.asyncFindIndex = asyncFindIndex;

const found = await array.asyncFindIndex(async element => {
    return element > 2;
});

console.log('Resolved Index ' + found);
Resolved Index 2
Clone this wiki locally