Saltar al contenido
Skillpedia
APIs y servidores (backend)48 mil · #4638

fp-async

Qué hace

Esta herramienta te ayuda a organizar y gestionar las operaciones asíncronas (tareas que tardan en completarse) en tu código, sobre todo cuando pueden fallar. Usa un método llamado `TaskEither` para que los errores se gestionen de forma clara y ordenada, evitando confusiones.

Cuándo usarla

  • ✓Cuando necesitas gestionar operaciones que tardan, como obtener datos de una API o guardar información en una base de datos.
  • ✓Si te cuesta organizar la gestión de errores en tu código asíncrono, con muchos bloques `try/catch` anidados.
  • ✓Para crear secuencias de operaciones asíncronas que deben ejecutarse en orden y gestionar sus errores de forma coherente.

Link de la skill

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

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-async/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo usar `TaskEither` para obtener datos de una API y asegurarme de que los errores de red se gestionen bien?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

La herramienta usa `TaskEither`, que funciona como una caja que puede contener un resultado correcto o un error. Te permite encadenar operaciones asíncronas, asegurando que si una falla, el error se capture y se gestione limpiamente sin interrumpir el flujo del programa.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

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> =>

…
Preguntas frecuentes

¿Qué es `TaskEither`?

`TaskEither` es una forma de representar una operación asíncrona que puede tener éxito o fallar. Piensa en ello como un paquete que contiene o bien el resultado esperado, o bien una descripción del error que se produjo.

¿Por qué usarlo en lugar de `try/catch`?

Usar `TaskEither` ayuda a evitar muchos bloques `try/catch` anidados, que pueden hacer el código confuso. Ofrece una forma más estructurada y clara de gestionar los errores en operaciones asíncronas.

¿Necesito saber programación avanzada para usarlo?

No necesariamente. Aunque usa algunos conceptos de programación funcional, la idea principal es simplificar la gestión de errores en operaciones que tardan en completarse, haciendo el código más legible.

Detalles

Descripción original del autor

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

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#4638
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas