Skip to main content

Overview

The fromAsyncThrowable function wraps an async function that might throw exceptions and converts it into a function that returns a ResultAsync. This is the async equivalent of fromThrowable and is safer than using fromPromise with a function call. fromAsyncThrowable is a top-level export that references ResultAsync.fromThrowable.

Type Signature

Parameters

  • fn: The async function to wrap (returns a Promise that might reject)
  • errorFn: Optional function to map caught errors to a known type E
    • If not provided, the raw error is used
    • Maps both thrown errors (synchronous) and rejected promises (asynchronous)

Return Value

Returns a new function with the same parameters as the original, but returns a ResultAsync instead of a Promise that might reject.

Why Use fromAsyncThrowable?

Not all functions that return a Promise are truly async. Some can throw synchronously before returning the promise:
With fromAsyncThrowable:

Basic Usage

Wrapping Database Operations

Wrapping Fetch Requests

Real-World Examples

Email Service

File Upload

External API with Retries

Chaining Operations

Comparison with fromPromise

Using fromPromise (Not Safe for Sync Throws)

Using fromAsyncThrowable (Safe)

Key Points

  • Wraps async functions that might throw
  • Catches both synchronous throws and asynchronous rejections
  • Safer than fromPromise when wrapping function calls
  • Returns a function that returns ResultAsync
  • Error mapper is optional but recommended for type safety
  • Use this instead of fromPromise when working with function references