Function retry

  • When an iterable throws or rejects, it retries getting the value specified number of times.

    Note that retries deplete values prior the operator that threw the error, and so it is often used in combination with operator repeat.

    import {pipe, tap, retry} from 'iter-ops';

    const i = pipe(
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    tap(value => {
    if (value % 2 === 0) {
    throw new Error(`fail-${value}`); // throw for all even numbers
    }
    }),
    retry(1) // retry 1 time
    );

    console.log(...i); //=> 1, 3, 5, 7, 9

    Above, we end up with just odd numbers, because we do not provide any repeat logic, and as a result, the retry simply jumps to the next value on each error.

    Type Parameters

    • T

    Parameters

    • attempts: number

    Returns Operation<T, T>

  • When an iterable throws or rejects, the callback is to return the flag, indicating whether we should retry getting the value one more time. When inside asynchronous pipeline, the callback can also return Promise<boolean>.

    import {pipe, tap, retry} from 'iter-ops';

    const i = pipe(
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    tap(value => {
    if (value % 2 === 0) {
    throw new Error(`fail-${value}`); // throw for all even numbers
    }
    }),
    retry(({attempt}) => {
    // available properties: {attempt, error, index, state}
    return attempt < 3; // make up to 3 retry attempts
    })
    );

    console.log(...i); //=> 1, 3, 5, 7, 9

    The callback is only invoked when there is a failure, and it receives an object with the following properties:

    • attempt - attempt index so far (starts with 0)
    • error - the error that was thrown
    • index - index of the iterable value that threw/rejected
    • state - state for the entire iteration session

    Note that retries deplete values prior the operator that threw the error, and so it is often used in combination with operator repeat.

    Type Parameters

    • T

    Parameters

    • retry: ((cb: {
          attempt: number;
          error: any;
          index: number;
          state: IterationState;
      }) => boolean | Promise<boolean>)
        • (cb): boolean | Promise<boolean>
        • Parameters

          • cb: {
                attempt: number;
                error: any;
                index: number;
                state: IterationState;
            }

          Returns boolean | Promise<boolean>

    Returns Operation<T, T>