Overview
ThefromAsyncThrowable 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 aPromisethat might reject)errorFn: Optional function to map caught errors to a known typeE- 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 aResultAsync instead of a Promise that might reject.
Why Use fromAsyncThrowable?
Not all functions that return aPromise are truly async. Some can throw synchronously before returning the promise:
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
fromPromisewhen wrapping function calls - Returns a function that returns
ResultAsync - Error mapper is optional but recommended for type safety
- Use this instead of
fromPromisewhen working with function references
Related
- fromThrowable() - For synchronous functions
- fromPromise() - For existing Promise instances
- fromSafePromise() - For Promises that never reject
- ResultAsync - The ResultAsync class