Overview
ThefromPromise 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: APromiseLike<T>that might rejecterrorHandler: Required function that maps the rejection value to a known error typeE- Receives
unknownas the error (the rejection value) - Must return a value of type
E
- Receives
Return Value
Returns aResultAsync<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
Error Handler is Required
UnlikefromThrowable, 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>toResultAsync<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
safeTryand other Result methods
Related
- fromAsyncThrowable() - For wrapping async functions
- fromSafePromise() - For Promises that never reject
- ResultAsync - The ResultAsync class
- safeTry() - For combining multiple async operations