Use andThen to sequence operations where the next step depends on the success of the previous one and might also fail. The callback must return a Result or ResultAsync. andThen flattens nested results, turning a ResultAsync<ResultAsync<A, E2>, E1> into a ResultAsync<A, E2>.
import { validateUser } from 'imaginary-validator'
import { insertUser } from 'imaginary-database'
import { sendNotification } from 'imaginary-service'
// assume signatures:
// validateUser(user: User): Result<User, Error>
// insertUser(user): ResultAsync<User, Error>
// sendNotification(user): ResultAsync<void, Error>
const resAsync = validateUser(user)
.andThen(insertUser)
.andThen(sendNotification)
// resAsync is a ResultAsync<void, Error>
resAsync.then((res: Result<void, Error>) => {
if(res.isErr()){
console.log("Oops, at least one step failed", res.error)
}
else{
console.log("User has been validated, inserted and notified successfully.")
}
})