Skip to content

Conversation

feelsantiago
Copy link

This is a neverThrow.safeTry inspired implementation to simulate Rust's ? operator.


Usage Example

import { Result } from '@sapphire/result';

const result = Result.safeTry(function* ({ $ }) {
  const first = yield* ok(1)[$];
  const second = yield* ok(1)[$];

  return ok(first + second);
});

result.match({
  ok: (value) => console.log(value), // 2
  err: (error) => console.log(error),
});

Yields at first error

const result = Result.safeTry(function* ({ $ }) {
  const first = yield* ok(1)[$];
  
  yield* err('Stop here');  

  const second = yield* ok(1)[$];

  return ok(first + second);
});

result.match({
  ok: (value) => console.log(value), 
  err: (error) => console.log(error), // error: Stop here
});

Async support

import { Result } from '@sapphire/result';

async function foo(): Promise<Result<number, never>> {
  return Result.fromAsync(async () => 1);
}

const result = Result.safeTry(function* ({ $, $async }) {
  const first = yield* ok(1)[$];
  const second = yield* $async(foo());

  return ok(first + second);
});

result.match({
  ok: (value) => console.log(value), // 2
  err: (error) => console.log(error),
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant