Skip to main content

Overview

The fromPromise function transforms a Promise<T> that might reject into a ResultAsync<T, E>. It allows you to handle Promise rejections in a type-safe way by mapping the rejection to a known error type. fromPromise is a top-level export that references ResultAsync.fromPromise.

Type Signature

Parameters

  • promise: A PromiseLike<T> that might reject
  • errorHandler: Required function that maps the rejection value to a known error type E
    • Receives unknown as the error (the rejection value)
    • Must return a value of type E

Return Value

Returns a ResultAsync<T, E> that:
  • Resolves to Ok<T> if the promise resolves successfully
  • Resolves to Err<E> if the promise rejects

Basic Usage

Converting a Simple Promise

Database Query

Real-World Examples

HTTP Request with Detailed Error Handling

File System Operations

Multiple Async Operations

Promise.all with Results

Streaming Response

Chaining with Other Methods

Important Considerations

fromPromise vs fromAsyncThrowableUse fromPromise when you already have a Promise instance:
Use fromAsyncThrowable when wrapping a function that might throw synchronously:

Error Handler is Required

Unlike fromThrowable, the error handler parameter is not optional for fromPromise. This is because:
  • Promise rejections can be of any type
  • TypeScript cannot infer a safe default error type
  • You must explicitly handle the unknown rejection value

Key Points

  • Converts Promise<T> to ResultAsync<T, E>
  • Error handler parameter is required
  • Maps promise rejections to a known error type
  • Use for existing Promise instances
  • For function wrapping, prefer fromAsyncThrowable
  • Works seamlessly with safeTry and other Result methods