Chaining Operations with Result
You'll learn how to compose multiple fallible operations elegantly using .map() and .flatMap() methods on Result objects, eliminating nested try-catch blocks.
Why Chaining Matters
Once you have a Result type that explicitly represents success or failure, you need a way to perform sequences of operations that might fail. Without proper chaining, you'd end up checking isOk repeatedly or nesting try-catch blocks—defeating the purpose of using Result in the first place.
The Core Idea
Think of chaining like an assembly line: if any station fails, the entire line stops gracefully without crashing. Each operation transforms the "good" value if present, or simply passes the error along unchanged.
.map() for Transformations
Use .map() when your operation cannot fail and just transforms the success value:
const result = Ok(5)
.map(n => n * 2) // Ok(10)
.map(n => n + 1); // Ok(11)
const failed = Err("oops")
.map(n => n * 2); // Still Err("oops"), map is skipped
.flatMap() for Fallible Operations
Use .flatMap() when your operation returns another Result (might fail):
function divide(a, b) {
return b === 0 ? Err("Division by zero") : Ok(a / b);
}
const result = Ok(10)
.flatMap(n => divide(n, 2)) // Ok(5)
.flatMap(n => divide(n, 0)); // Err("Division by zero")
Without .flatMap(), you'd get nested Results: Ok(Ok(5)). The "flat" part unwraps one level automatically.
Real-World Flow
parseJSON(input)
.map(data => data.userId)
.flatMap(fetchUser)
.map(user => user.email)
.match(
email => console.log(email),
err => console.error(err)
);
No try-catch pyramids, just a clean pipeline.
Key Takeaway: Use .map() to transform success values and .flatMap() to chain operations that return Results, creating readable, composable error-handling pipelines without nested conditionals.