Task<T>

Async operations with cancellation and error handling

Enhanced async/await with cancellation support, progress tracking, and structured error handling

What is Task<T>?

Task provides structured async operations with built-in cancellation, progress tracking, and error handling. Unlike Promises, Tasks can be cancelled and provide detailed error context.

// Task v2: All operations return TaskOutcome<T>
const syncResult = Task().Sync(() => "success")
// Returns: TaskSuccess<string> (extends TaskOutcome<string>)

const _asyncResult = Task().Async(async () => {
  await new Promise((resolve) => setTimeout(resolve, 100))
  return "async success"
})
// Returns: Promise<TaskSuccess<string>>

// Error handling
const errorResult = Task().Sync(() => {
  throw new Error("Something failed")
})
// Returns: TaskFailure<string>

// Transform successful results
const _transformed = Task().Sync(() => 42)
const doubled = _transformed.map((value) => value * 2)

// Chain operations with error handling
const _chained = Task().Sync(() => 5)
const _chainResult = _chained.flatMap((value) => Right(value * 2))

Key Features

Named Tasks

Debug async operations easily with named task contexts

Cancellation

Cancel ongoing operations gracefully when they're no longer needed

Progress Tracking

Monitor long-running operations with progress callbacks

Error Context

Rich error information including task name and stack traces

Common Patterns

Sync and Async Tasks

// Synchronous task
const sync = Task().Sync(
  () => 42,
  (err) => new Error("Failed"),
)

// Asynchronous task
const async = Task().Async(
  async () => await fetchData(),
  async (err) => new Error("Fetch error"),
)

Error Handling with Context

try {
  await Task({ name: "DataProcessor" }).Async(() => {
    throw new Error("Processing failed")
  })
} catch (error) {
  console.log(error.taskInfo.name) // "DataProcessor"
}

Converting Promises

const getUser = Task.fromPromise(fetchAPI, { name: "UserFetch" })

When to Use Task

Long-running async operations that might be cancelled

File uploads, downloads, expensive computations

Operations that need progress tracking

Batch processing, migrations, data imports

When you need better error context than Promises provide

Complex workflows, debugging production issues