Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)48k · #4638

fp-async

Skill này làm gì

Công cụ này giúp tổ chức và quản lý các thao tác bất đồng bộ (tác vụ cần thời gian để hoàn thành) trong mã, đặc biệt khi chúng có thể thất bại. Nó dùng một phương pháp gọi là `TaskEither` để đảm bảo lỗi được xử lý rõ ràng và có tổ chức, tránh nhầm lẫn.

Khi nào nên dùng

  • ✓Khi bạn cần xử lý các thao tác tốn thời gian, như lấy dữ liệu từ API hoặc lưu thông tin vào cơ sở dữ liệu.
  • ✓Khi bạn gặp khó khăn trong việc tổ chức xử lý lỗi trong mã bất đồng bộ có nhiều khối `try/catch` lồng nhau.
  • ✓Khi bạn muốn tạo chuỗi thao tác bất đồng bộ phải chạy theo thứ tự và được quản lý lỗi nhất quán.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-async/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-async/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 từ API và đảm bảo lỗi mạng được xử lý?”

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

Cách hoạt động

Công cụ dùng `TaskEither`, giống như một chiếc hộp có thể chứa kết quả thành công hoặc một lỗi. Nó cho phép bạn nối các thao tác bất đồng bộ lại với nhau, đảm bảo nếu một thao tác thất bại thì lỗi được ghi nhận và xử lý gọn gàng mà không làm gián đoạn chương trình.

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.

Practical Async Patterns with fp-ts

Stop writing nested try/catch blocks. Stop losing error context. Start building clean async pipelines that handle errors properly.

TaskEither is simply an async operation that tracks success or failure. That's it. No fancy terminology needed.

Detailed Guide

Read the detailed guide before executing this skill. It retains the complete procedure and reference material. Treat its safety, prerequisites, and validation requirements as mandatory. For focused work, load the relevant sections; for end-to-end work, read the guide completely.

When to Use

  • You need async error handling in TypeScript with TaskEither.
  • The task involves wrapping Promises, composing API calls, or replacing nested try/catch flows.
  • You want practical fp-ts async patterns instead of academic explanations.
// TaskEither<Error, User> means:
// "An async operation that either fails with Error or succeeds with User"

5. Real API Examples

Complete Fetch Wrapper

// types.ts
interface ApiError {
  code: string
  message: string
  status: number
  details?: unknown
}

// api.ts
const createApiError = (
  code: string,
  message: string,
  status: number,
  details?: unknown
): ApiError => ({ code, message, status, details })

const request = <T>(
  url: string,
  options: RequestInit = {}
): TE.TaskEither<ApiError, T> =>
  TE.tryCatch(
    async () => {
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
        ...options,
      })

      if (!response.ok) {
        const body = await response.json().catch(() => ({}))
        throw createApiError(
          body.code || 'HTTP_ERROR',
          body.message || response.statusText,
          response.status,
          body
        )
      }

      // Handle 204 No Content
      if (response.status === 204) {
        return undefined as T
      }

      return response.json()
    },
    (error): ApiError => {
      if (typeof error === 'object' && error !== null && 'code' in error) {
        return error as ApiError
      }
      return createApiError(
        'NETWORK_ERROR',
        error instanceof Error ? error.message : 'Request failed',
        0
      )
    }
  )

// API client
const api = {
  get: <T>(url: string) => request<T>(url),

  post: <T>(url: string, body: unknown) =>
    request<T>(url, {
      method: 'POST',
      body: JSON.stringify(body)
    }),

  put: <T>(url: string, body: unknown) =>
    request<T>(url, {
      method: 'PUT',
      body: JSON.stringify(body)
    }),

  delete: (url: string) =>
    request<void>(url, { method: 'DELETE' }),
}

// Usage
const getUser = (id: string) => api.get<User>(`/api/users/${id}`)
const createUser = (data: CreateUserDto) => api.post<User>('/api/users', data)
const updateUser = (id: string, data: UpdateUserDto) => api.put<User>(`/api/users/${id}`, data)
const deleteUser = (id: string) => api.delete(`/api/users/${id}`)

Database Operations (Prisma Example)

import { PrismaClient, Prisma } from '@prisma/client'

type DbError =
  | { _tag: 'NotFound'; entity: string; id: string }
  | { _tag: 'UniqueViolation'; field: string }
  | { _tag: 'ConnectionError'; cause: unknown }

const prisma = new PrismaClient()

const wrapPrisma = <T>(
  operation: () => Promise<T>
): TE.TaskEither<DbError, T> =>
  TE.tryCatch(
    operation,
    (error): DbError => {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        if (error.code === 'P2002') {
          const field = (error.meta?.target as string[])?.join(', ') || 'unknown'
          return { _tag: 'UniqueViolation', field }
        }
        if (error.code === 'P2025') {
          return { _tag: 'NotFound', entity: 'Record', id: 'unknown' }
        }
      }
      return { _tag: 'ConnectionError', cause: error }
    }
  )

// Repository pattern
const userRepository = {
  findById: (id: string): TE.TaskEither<DbError, User> =>
    pipe(
      wrapPrisma(() => prisma.user.findUnique({ where: { id } })),
      TE.chain(user =>
        user
          ? TE.right(user)
          : TE.left({ _tag: 'NotFound', entity: 'User', id })
      )
    ),

  findByEmail: (email: string): TE.TaskEither<DbError, User | null> =>
    wrapPrisma(() => prisma.user.findUnique({ where: { email } })),

  create: (data: CreateUserInput): TE.TaskEither<DbError, User> =>

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

`TaskEither` là gì?

`TaskEither` là cách biểu diễn một thao tác bất đồng bộ có thể thành công hoặc thất bại. Hãy hình dung nó như một gói chứa kết quả mong đợi hoặc mô tả lỗi đã xảy ra.

Tại sao dùng cái này thay vì `try/catch`?

Dùng `TaskEither` giúp tránh nhiều khối `try/catch` lồng nhau, vốn có thể khiến mã rối rắm. Nó cung cấp cách xử lý lỗi có cấu trúc và rõ ràng hơn cho các thao tác bất đồng bộ.

Tôi có cần biết lập trình nâng cao để dùng không?

Không nhất thiết. Mặc dù dùng một số khái niệm lập trình hàm, ý chính là đơn giản hóa việc xử lý lỗi cho các thao tác tốn thời gian, giúp mã dễ đọc hơn.

Chi tiết

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

Practical async patterns using TaskEither - clean pipelines instead of try/catch hell, with real API examples

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#4638
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ự