method Result.prototype.andThen
Result.prototype.andThen<U, F extends BaseError>(fn: (value: T) => Result<U, F>): Result<U, E | F>

Chains operations that return Results (also known as flatMap).

If this Result is Ok, calls the function with the Ok value and returns its Result. If this Result is Err, returns the Err without calling the function.

Examples

Example 1

function parseNumber(s: string): Result<number, ValidationError> {
  const n = Number(s);
  if (isNaN(n)) {
    return Result.err(new ValidationError("Not a number"));
  }
  return Result.ok(n);
}

const result = Result.ok("42")
  .andThen(parseNumber)
  .map(x => x * 2);

Type Parameters

The type of the new Ok value

F extends BaseError

The type of the new error

Parameters

fn: (value: T) => Result<U, F>

Function that takes the Ok value and returns a new Result

Return Type

Result<U, E | F>

The Result from calling fn, or the original Err

Usage

import { Result } from "result/mod.ts";