| name | fp-taskeither-ref |
| description | Quick reference for TaskEither. Use when user needs async error handling, API calls, or Promise-based operations that can fail. |
| version | 1.0.0 |
| tags | ["fp-ts","taskeither","async","promise","error-handling","quick-reference"] |
TaskEither Quick Reference
TaskEither = async operation that can fail. Like Promise<Either<E, A>>.
Create
import * as TE from 'fp-ts/TaskEither'
TE.right(value)
TE.left(error)
TE.tryCatch(asyncFn, toError)
TE.fromEither(either)
Transform
TE.map(fn)
TE.mapLeft(fn)
TE.flatMap(fn)
TE.orElse(fn)
Execute
const result = await myTaskEither()
await pipe(
myTaskEither,
TE.match(
(err) => console.error(err),
(val) => console.log(val)
)
)()
Common Patterns
import { pipe } from 'fp-ts/function'
import * as TE from 'fp-ts/TaskEither'
const fetchUser = (id: string) => TE.tryCatch(
() => fetch(`/api/users/${id}`).then(r => r.json()),
(e) => ({ type: 'NETWORK_ERROR', message: String(e) })
)
pipe(
fetchUser('123'),
TE.flatMap(user => fetchPosts(user.id)),
TE.map(posts => posts.length)
)
import { sequenceT } from 'fp-ts/Apply'
sequenceT(TE.ApplyPar)(
fetchUser('1'),
fetchPosts('1'),
fetchComments('1')
)
pipe(
fetchUser('123'),
TE.orElse(() => TE.right(defaultUser)),
TE.getOrElse(() => defaultUser)
)
vs async/await
async function getUser(id: string) {
try {
const res = await fetch(`/api/users/${id}`)
return await res.json()
} catch (e) {
return null
}
}
const getUser = (id: string) => pipe(
TE.tryCatch(() => fetch(`/api/users/${id}`), toNetworkError),
TE.flatMap(res => TE.tryCatch(() => res.json(), toParseError))
)
Use TaskEither when you need typed errors for async operations.