Skip to main content

Overview

The safeTry function allows you to write error handling code that resembles Rust’s ? operator using JavaScript generator syntax. It eliminates the boilerplate of repeatedly checking if a Result is Ok or Err, making your code more concise and readable.

Type Signature

How It Works

safeTry evaluates a generator function and:
  • Returns the first Err that is yielded, short-circuiting execution
  • Otherwise, returns the final Result that is returned from the generator
Inside the generator, you use yield* with a Result to unwrap its value or early-return if it’s an Err.

Basic Usage

Synchronous Example

Without safeTry (More Boilerplate)

Asynchronous Usage

For async operations, use an async function* generator:

Mixing Sync and Async Results

Chaining Operations

You can combine safeTry with other Result methods:

Real-World Example

Key Points

  • Use function* for synchronous generators, async function* for async
  • Use yield* (not yield) to unwrap Results
  • The generator must return a Result or ResultAsync
  • Execution stops at the first Err encountered
  • You can mix sync and async Results in async generators

Comparison to Rust

In Rust:
With safeTry: