Hyperlinkv0.8.0-beta.28

Result

Result.genconsteffect/Result.ts:1560
<Self, K, A>(
  ...args:
    | [self: Self, body: (this: Self) => Generator<K, A, never>]
    | [body: () => Generator<K, A, never>]
): Result<
  A,
  [K] extends [Gen.Variance<ResultTypeLambda, any, any, infer E>]
    ? E
    : [K] extends [Result<any, infer E>]
    ? E
    : never
>

Provides generator-based syntax for composing Result values sequentially.

When to use

Use when you need generator syntax to compose sequential Result computations instead of nested flatMap calls.

Details

  • Use yield* to unwrap a Result inside the generator; if any yielded Result is a Failure, the generator short-circuits and returns that failure
  • The return value of the generator is wrapped in Success
  • Evaluated eagerly and synchronously (unlike Effect.gen)

Example (Composing multiple Results)

import { Result } from "effect"

const result = Result.gen(function*() {
  const a = yield* Result.succeed(1)
  const b = yield* Result.succeed(2)
  return a + b
})

console.log(result)
// Output: { _tag: "Success", success: 3, ... }
generatorsflatMapall
Source effect/Result.ts:156013 lines
export const gen: Gen.Gen<ResultTypeLambda> = (...args) => {
  const f = args.length === 1 ? args[0] : args[1].bind(args[0])
  const iterator = f()
  let state: IteratorResult<any> = iterator.next()
  while (!state.done) {
    const current = state.value
    if (isFailure(current)) {
      return current
    }
    state = iterator.next(current.success as never)
  }
  return succeed(state.value) as any
}