Overview
Similar tomap, but the mapping function must return a new Result. This is useful for chaining computations where each step might fail, and is excellent for flattening nested Results.
Signature
Parameters
(t: T) => Result<U, F>
required
A function that takes the Ok value and returns a new Result. This function is only called if the current Result is Ok.
Returns
Returns a newResult<U, E | F> where:
- If the original Result is
Ok(value), returns the result off(value) - If the original Result is
Err(error), returnsErr(error)without callingf - Error types from both Results are combined as a union type
Examples
Basic Chaining
Flattening Nested Results
Sequential Operations
Distinct Error Types (v4.1.0+)
Real-World Example
Error Short-Circuiting
Implementation Details
From the source code (result.ts:337-339):Err (result.ts:461-463):
Notes
andThenis also known asflatMaporbindin other functional programming libraries- Perfect for avoiding nested Results like
Result<Result<T, E2>, E1> - All error types are preserved as a union type
- For async operations, use asyncAndThen()
- The operation short-circuits on the first error
Related
- Result.map() - Transform values without returning a Result
- Result.asyncAndThen() - Chain async operations
- Result.orElse() - Chain operations on the error path