본문으로 건너뛰기
Skillpedia
일반 코딩48k · #4648

fp-taskeither-ref

하는 일

TaskEither는 실패할 수 있는 비동기 작업(시간이 걸리는 작업)을 처리하는 방법입니다. 오류를 명확하고 체계적으로 관리하도록 합니다.

사용하는 경우

  • ✓실패할 수 있는 외부 API를 호출할 때.
  • ✓명시적인 오류 처리가 필요한 Promise로 작업할 때.
  • ✓각 단계에서 오류가 날 수 있는 비동기 작업의 연속을 만들 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-taskeither-ref/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“TaskEither를 사용해 사용자 데이터를 가져오고, 네트워크 오류나 형식 오류를 처리하려면 어떻게 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

Promise처럼 작동하지만, 단순히 성공하거나 실패하는 대신 성공(데이터 포함) 또는 특정 오류 중 하나를 반환합니다. 작업을 연결하거나, 성공을 변환하거나, 오류에서 복구할 수 있습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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.

자주 묻는 질문

「지연 생성」은 무슨 뜻인가요?

작업이 정의될 때가 아니라, 명시적으로 호출될 때만 실행된다는 뜻입니다.

`map`과 `flatMap`의 차이는 무엇인가요?

`map`은 성공 값을 변환하지만 결과는 여전히 TaskEither입니다. `flatMap`은 작업을 연결하며, 전달하는 함수도 TaskEither를 반환해 더 복잡한 연속 작업이 가능합니다.

작업은 어떻게 실행하나요?

정의한 함수를 호출하면(Promise를 반환합니다) `await`를 사용해 결과를 받습니다. 결과는 `Either`(성공 또는 오류)입니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
48k
순위
#4648
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬