Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #4648

fp-taskeither-ref

Skill này làm gì

TaskEither là cách xử lý các thao tác bất đồng bộ (cần thời gian) có thể thất bại. Nó đảm bảo lỗi được quản lý rõ ràng và có tổ chức.

Khi nào nên dùng

  • ✓Khi gọi các API bên ngoài có thể thất bại.
  • ✓Khi làm việc với Promise cần xử lý lỗi một cách rõ ràng.
  • ✓Khi xây dựng chuỗi các thao tác bất đồng bộ mà mỗi bước có thể tạo ra lỗi.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-taskeither-ref/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-taskeither-ref/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm thế nào để dùng TaskEither để lấy dữ liệu người dùng và đảm bảo các lỗi mạng hoặc lỗi định dạng được xử lý?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó hoạt động giống một promise, nhưng thay vì chỉ thành công hoặc thất bại, nó trả về một kết quả hoặc là thành công (kèm dữ liệu) hoặc là một lỗi cụ thể. Bạn có thể nối các thao tác, biến đổi kết quả thành công hoặc phục hồi từ lỗi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

TaskEither Quick Reference

TaskEither = async operation that can fail. Its shape is () => Promise<Either<E, A>>: construction is lazy.

When to Use

  • You need a quick fp-ts reference for async operations that can fail.
  • The task involves API calls, Promise wrapping, or composing asynchronous error-handling pipelines.
  • You want a concise cheat sheet for TaskEither operators and patterns.

Create

import * as TE from 'fp-ts/TaskEither'
import * as T from 'fp-ts/Task'

TE.right(value)          // Async success
TE.left(error)           // Async failure
TE.tryCatch(asyncFn, toError)  // Promise → TaskEither
TE.fromEither(either)    // Either → TaskEither

Transform

TE.map(fn)               // Transform success value
TE.mapLeft(fn)           // Transform error
TE.flatMap(fn)           // Chain (fn returns TaskEither)
TE.orElse(fn)            // Recover from error

Execute

// 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)
  )
)()

Common Patterns

import { pipe } from 'fp-ts/function'
import * as TE from 'fp-ts/TaskEither'
import * as T from 'fp-ts/Task'

// Wrap fetch
const fetchUser = (id: string, signal: AbortSignal) => TE.tryCatch(
  async () => {
    const response = await fetch(`/api/users/${encodeURIComponent(id)}`, { signal })
    if (!response.ok) throw new Error(`HTTP ${response.status}`)
    const body: unknown = await response.json()
    return validateUser(body) // Application schema validator; throws on invalid data
  },
  (e) => ({ type: 'NETWORK_ERROR', message: String(e) })
)

// Chain async calls
pipe(
  fetchUser('123', signal),
  TE.flatMap(user => fetchPosts(user.id)),
  TE.map(posts => posts.length)
)

// Parallel calls
import { sequenceT } from 'fp-ts/Apply'
sequenceT(TE.ApplyPar)(
  fetchUser('1', signal),
  fetchPosts('1'),
  fetchComments('1')
)

// With recovery
pipe(
  fetchUser('123', signal),
  TE.orElse(() => TE.right(defaultUser)),
  TE.getOrElse(() => T.of(defaultUser))
)

vs 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, signal: AbortSignal) => pipe(
  TE.tryCatch(() => fetch(`/api/users/${encodeURIComponent(id)}`, { signal }), toNetworkError),
  TE.flatMap(res => TE.tryCatch(async () => {
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    return validateUser(await res.json())
  }, toParseError))
)

Use TaskEither when you need typed errors for async operations.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Reference scope

These are fp-ts 2.x fragments. Supply application variables, types, validators and imports, and check the installed version. map does not catch thrown exceptions. Task has no typed error channel; an improperly wrapped promise can still reject. Use tryCatch at fallible boundaries.

Supply a caller-owned timeout/abort signal and validate response schemas. Parallel application calls need bounded concurrency and authorization for their data, costs and effects; ApplyPar does not cancel work automatically on failure. Error callbacks must redact secrets and private payloads.

Official API: fp-ts modules.

Câu hỏi thường gặp

“Lazy construction” nghĩa là gì?

Nghĩa là thao tác chỉ được thực thi khi bạn gọi nó một cách rõ ràng, chứ không phải khi nó được định nghĩa.

Sự khác nhau giữa `map` và `flatMap` là gì?

`map` biến đổi giá trị thành công, nhưng kết quả vẫn là TaskEither. `flatMap` nối các thao tác, trong đó hàm được truyền vào cũng trả về TaskEither, cho phép các chuỗi phức tạp hơn.

Làm thế nào để thực thi thao tác?

Bạn cần gọi hàm đã định nghĩa (nó trả về một Promise) và dùng `await` để lấy kết quả, là một `Either` (thành công hoặc lỗi).

Chi tiết

Mô tả gốc của tác giả

Quick reference for TaskEither. Use when user needs async error handling, API calls, or Promise-based operations that can fail.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#4648
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự