Overview
ThesafeTry 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
Errthat is yielded, short-circuiting execution - Otherwise, returns the final
Resultthat is returned from the generator
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 anasync function* generator:
Mixing Sync and Async Results
Chaining Operations
You can combinesafeTry with other Result methods:
Real-World Example
Key Points
- Use
function*for synchronous generators,async function*for async - Use
yield*(notyield) to unwrap Results - The generator must return a
ResultorResultAsync - Execution stops at the first
Errencountered - You can mix sync and async Results in async generators
Comparison to Rust
In Rust:safeTry: