Converts a Promise<T>
into a Result<T, E>
. Note that if the promise rejects, an Err<E>
with the rejected value
will be returned, even if the rejected value is not of type E
.
For type-safe error handling, use mapErr
to transform and validate errors:
The type of the success value
The type of the error value; defaults to unknown
The promise to convert.
A Result<T, E>
that resolves to the value of the promise if it resolves, or an Err
if it rejects.
// Basic usage
const result = await Ok.from(Promise.resolve(42));
console.log(result.unwrap()); // 42
// Error handling with mapErr;
// `result` is of type `Result<Response, NetworkError | UnknownError>`
const result = (await Ok.from(fetch('/api/users')))
.mapErr((error: unknown) => {
if (error instanceof TypeError) {
return new NetworkError('Network request failed', { cause: error });
}
return new UnknownError('Unknown error occurred', { cause: error });
});
// Handling specific error types;
// `result` is of type `Result<DatabaseResponse, DuplicateEntryError | TableNotFoundError | DatabaseError | UnknownError>`
const result = (await Ok.from(databaseQuery()))
.mapErr((error: unknown) => {
if (error instanceof DatabaseError) {
switch (error.code) {
case 'ER_DUP_ENTRY':
return new DuplicateEntryError('Record already exists');
case 'ER_NO_SUCH_TABLE':
return new TableNotFoundError('Table does not exist');
default:
return new DatabaseError('Database operation failed', { cause: error });
}
}
return new UnknownError('Unexpected error', { cause: error });
});
// Handling AggregateError from Promise.allSettled;
// `results` is of type `Result<PromiseSettledResult<number>[], ValidationError | UnknownError>`
const results = await Ok.from(Promise.allSettled([promise1, promise2]))
.mapErr((error: unknown) => {
if (error instanceof AggregateError) {
return new ValidationError('Multiple errors occurred', error.errors);
}
return new UnknownError('Unexpected error', { cause: error });
});
// Handling AbortError;
// `result` is of type `Result<Response, CancelledError | NetworkError>`
const result = await Ok.from(fetch(url, { signal: abortController.signal }))
.mapErr((error: unknown) => {
if (error instanceof AbortError) {
return new CancelledError('Request was cancelled');
}
return new NetworkError('Network request failed', { cause: error });
});
Executes a function that might throw and returns a Result
containing the return value or the thrown error.
Note: TypeScript cannot automatically infer the error types from functions. You may need to provide explicit type annotations for better type safety.
The type of the return value
The type of the error; defaults to unknown
A function that might throw an error.
A Result
containing the return value or the thrown error.
Creates a new
Ok
result.