
关于
TaskEither 快速参考。适用于用户需要异步错误处理、API 调用或可能失败的基于 Promise 的操作。
name: fp-taskeither-ref description: TaskEither 快速参考。当用户需要异步错误处理、API 调用或可能失败的基于 Promise 的操作时使用。 risk: unknown source: community version: 1.0.0 tags: [fp-ts, taskeither, async, promise, error-handling, quick-reference]
TaskEither 快速参考
TaskEither = 可能失败的异步操作。类似 Promise<Either<E, A>>。
何时使用
- 你需要异步操作中可能失败的 fp-ts 快速参考。
- 任务涉及 API 调用、Promise 包装或组合异步错误处理管道。
- 你需要
TaskEither操作符和模式的简洁速查表。
创建
import * as TE from 'fp-ts/TaskEither'
TE.right(value) // Async success
TE.left(error) // Async failure
TE.tryCatch(asyncFn, toError) // Promise → TaskEither
TE.fromEither(either) // Either → TaskEither
转换
TE.map(fn) // Transform success value
TE.mapLeft(fn) // Transform error
TE.flatMap(fn) // Chain (fn returns TaskEither)
TE.orElse(fn) // Recover from error
执行
// TaskEither is lazy - must call () to run
const result = await myTaskEither() // Either<E, A>
// Or pattern match
await pipe(
myTaskEither,
TE.match(
(err) => console.error(err),
(val) => console.log(val)
)
)()
常见模式
import { pipe } from 'fp-ts/function'
import * as TE from 'fp-ts/TaskEither'
// Wrap fetch
const fetchUser = (id: string) => TE.tryCatch(
() => fetch(`/api/users/${id}`).then(r => r.json()),
(e) => ({ type: 'NETWORK_ERROR', message: String(e) })
)
// Chain async calls
pipe(
fetchUser('123'),
TE.flatMap(user => fetchPosts(user.id)),
TE.map(posts => posts.length)
)
// Parallel calls
import { sequenceT } from 'fp-ts/Apply'
sequenceT(TE.ApplyPar)(
fetchUser('1'),
fetchPosts('1'),
fetchComments('1')
)
// With recovery
pipe(
fetchUser('123'),
TE.orElse(() => TE.right(defaultUser)),
TE.getOrElse(() => defaultUser)
)
对比 async/await
// ❌ async/await - errors hidden
async function getUser(id: string) {
try {
const res = await fetch(`/api/users/${id}`)
return await res.json()
} catch (e) {
return null // Error info lost
}
}
// ✅ TaskEither - errors typed and composable
const getUser = (id: string) => pipe(
TE.tryCatch(() => fetch(`/api/users/${id}`), toNetworkError),
TE.flatMap(res => TE.tryCatch(() => res.json(), toParseError))
)
当你需要异步操作的类型化错误时使用 TaskEither。
限制
- 仅在任务明确匹配上述范围时使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少必需的输入、权限、安全边界或成功标准,请停下来要求澄清。
兼容工具
Claude CodeCursor
标签
前端开发