Langsung ke konten
Skillpedia
Pemrograman umum48k · #4648

fp-taskeither-ref

Fungsinya

TaskEither adalah cara untuk menangani operasi asinkron (yang membutuhkan waktu) yang mungkin gagal. Cara ini memastikan error ditangani dengan jelas dan terorganisir.

Kapan dipakai

  • ✓Ketika melakukan pemanggilan ke API eksternal yang mungkin gagal.
  • ✓Ketika bekerja dengan Promise yang membutuhkan penanganan error secara eksplisit.
  • ✓Ketika membangun rangkaian operasi asinkron di mana setiap langkah bisa menghasilkan error.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-taskeither-ref/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Bagaimana cara menggunakan TaskEither untuk mengambil data pengguna dan memastikan error jaringan atau format ditangani?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Cara kerjanya mirip seperti promise yang, alih-alih hanya berhasil atau gagal, mengembalikan hasil yang bisa berupa sukses (dengan data) atau error tertentu. Anda dapat merangkai operasi, mengubah hasil sukses, atau memulihkan diri dari error.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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.

Pertanyaan umum

Apa maksud 'lazy construction'?

Artinya operasi hanya dijalankan ketika Anda memanggilnya secara eksplisit, bukan saat didefinisikan.

Apa perbedaan `map` dan `flatMap`?

`map` mengubah nilai sukses, tetapi hasilnya tetap berupa TaskEither. `flatMap` merangkai operasi, di mana fungsi yang diberikan juga mengembalikan TaskEither, sehingga memungkinkan rangkaian yang lebih kompleks.

Bagaimana cara menjalankan operasinya?

Anda perlu memanggil fungsi yang sudah didefinisikan (fungsi itu mengembalikan Promise) dan menggunakan `await` untuk mendapatkan hasilnya, yang berupa `Either` (sukses atau error).

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
48k
Peringkat
#4648
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa