Skip to main content

Why Chain Operations?

Chaining allows you to compose multiple fallible operations without nested conditionals or try-catch blocks:

Using andThen for Sequential Operations

Basic andThen Pattern

andThen() is used when your callback returns another Result:
If any step fails, the chain short-circuits:

Real-World Example: User Registration

1

Define validation functions

Each function returns a Result to handle validation errors:
2

Chain the operations

Compose all validation and creation steps:
3

Handle the result

The chain stops at the first error, providing clear feedback:

Flattening Nested Results

andThen automatically flattens nested Results:

map vs andThen

Understand when to use each method:
When your callback returns a regular value (not a Result):

Error Context with mapErr

Add context to errors as they flow through the chain:

Distinct Error Types

Starting from v4.1.0, andThen supports returning different error types:

Advanced Pattern: Railway-Oriented Programming

Build complex pipelines that handle success and failure tracks:

Next Steps

Async Operations

Learn how to chain asynchronous operations with ResultAsync

Combining Results

Work with multiple Results at once using combine