ResultAsync<T, E>
Represents an asynchronous Result that wraps a Promise.
ResultAsync implements PromiseLike<Result<T, E>>, which means it can be awaited
directly or used with .then() chains. It provides the same API as Result but
for asynchronous operations.
Sinceโ
2.0.0
Exampleโ
const asyncResult = okAsync(Promise.resolve("hello"));
// Can be awaited directly
const result = await asyncResult;
if (result.isOk()) {
console.log(result.value); // "hello"
}
// Or used with .then()
asyncResult.then(result => {
if (result.isOk()) {
console.log(result.value);
}
});
Type Parametersโ
T: Tโ
The type of the success value
E: Eโ
The type of the error value
Implementsโ
PromiseLike<Result<T,E>>
Constructorsโ
Constructorโ
Creates a new ResultAsync instance.
res:
Promise<Result<T, E>>โ Promise that resolves to a Result
Returns:ResultAsync<T, E>
Methodsโ
fromSafePromise()โ
Creates a ResultAsync from a Promise that is guaranteed to resolve successfully. This method assumes the Promise will never reject, so use with caution.
Type Parametersโ
T: Tโ
The type of the value in the Promise
E: E = neverโ
The type of the error (defaults to never)
promise:
Promise<T>โ Promise that will resolve to a value
Returns:ResultAsync<T, E>โ A new ResultAsync that will resolve to Ok(value)
Exampleโ
const promise = Promise.resolve(42);
const result = ResultAsync.fromSafePromise(promise);
const resolved = await result;
// resolved is Ok(42)
fromPromise()โ
Creates a ResultAsync from a Promise that may reject. The errorFn parameter is used to transform any rejection into an error value.
Type Parametersโ
T: Tโ
The type of the value in the Promise
E: Eโ
The type of the error
promise:
Promise<T>โ Promise that may resolve or reject
errorFn:(e) => Eโ Function to transform rejections into error values
Returns:ResultAsync<T, E>โ A new ResultAsync that will resolve to Ok(value) or Err(error)
Exampleโ
const fetchUser = (id: string) =>
fetch(`/api/users/${id}`).then(r => r.json());
const result = ResultAsync.fromPromise(
fetchUser("123"),
(error) => `Failed to fetch user: ${error}`
);
const resolved = await result;
if (resolved.isOk()) {
console.log(resolved.value); // User data
} else {
console.log(resolved.error); // Error message
}
fromThrowable()โ
Wraps an async function with try-catch error handling, creating a new function that returns a ResultAsync instead of throwing exceptions.
Uses unknown types for maximum type safety and modern TypeScript syntax.
Type Parametersโ
A: A extends unknown[]โ
The types of the function arguments
R: Rโ
The return type of the async function
E: E = unknownโ
The type of the error
fn:
(...args) => Promise<R>โ Async function to wrap with error handling
errorFn?:(err) => Eโ Optional function to transform thrown errors
Returns:A new function that returns a ResultAsync instead of throwingโ > (...args):ResultAsync<R,E>
args:
...A
Returns:ResultAsync<R, E>
Exampleโ
const fetchUser = async (id: string) => {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
};
const safeFetchUser = ResultAsync.fromThrowable(
fetchUser,
(error) => `User fetch failed: ${error}`
);
const result = await safeFetchUser("123");
if (result.isOk()) {
console.log(result.value); // User data
} else {
console.log(result.error); // Error message
}
combine()โ
Combines multiple ResultAsync instances into a single ResultAsync. Returns the first error encountered, or all values if all ResultAsyncs are Ok.
Uses unknown types for maximum type safety and compatibility.
Type Parametersโ
T: T extends ResultAsync<unknown, unknown>[]โ
The type of the ResultAsync array
asyncResultList:
Tโ Array of ResultAsync instances to combine
Returns:ResultAsync<unknown[], unknown>โ A ResultAsync containing an array of all values, or the first error
Exampleโ
const results = [
okAsync(Promise.resolve(1)),
okAsync(Promise.resolve(2)),
okAsync(Promise.resolve(3))
];
const combined = ResultAsync.combine(results);
const resolved = await combined;
// resolved is Ok([1, 2, 3])
const withError = [
okAsync(Promise.resolve(1)),
errAsync("second failed"),
okAsync(Promise.resolve(3))
];
const failed = ResultAsync.combine(withError);
const errorResult = await failed;
// errorResult is Err("second failed")
combineWithAllErrors()โ
Combines multiple ResultAsync instances into a single ResultAsync. Collects all errors encountered, or returns all values if all ResultAsyncs are Ok.
Unlike combine(), this method doesn't stop at the first error but collects
all errors from failed ResultAsyncs into an array.
Type Parametersโ
T: T extends ResultAsync<unknown, unknown>[]โ
The type of the ResultAsync array
asyncResultList:
Tโ Array of ResultAsync instances to combine
Returns:ResultAsync<unknown[], unknown[]>โ A ResultAsync containing an array of all values, or an array of all errors
Exampleโ
const results = [
okAsync(1),
errAsync("error1"),
okAsync(3),
errAsync("error2")
];
const combined = ResultAsync.combineWithAllErrors(results);
const resolved = await combined;
// resolved is Err(["error1", "error2"])
const allSuccess = [okAsync(1), okAsync(2), okAsync(3)];
const success = ResultAsync.combineWithAllErrors(allSuccess);
const values = await success;
// values is Ok([1, 2, 3])
map()โ
Transforms the success value using the provided function. If this resolves to an error result, the error is preserved unchanged. The transformation function can be synchronous or asynchronous.
Optimized for efficient Promise handling and type safety.
Type Parametersโ
A: Aโ
The type of the transformed value
f:
(t) => A | Promise<A>โ Function to transform the success value (can returnPromise<A>)
Returns:ResultAsync<A, E>โ A new ResultAsync with the transformed value or the original error
Exampleโ
const result = okAsync(Promise.resolve(5));
// Synchronous transformation
const doubled = result.map(x => x * 2);
const resolved = await doubled; // Ok(10)
// Asynchronous transformation
const fetched = result.map(async x => {
const response = await fetch(`/api/data/${x}`);
return response.json();
});
const data = await fetched; // Ok(data)
mapErr()โ
Transforms the error value using the provided function. If this resolves to a success result, the value is preserved unchanged. The transformation function can be synchronous or asynchronous.
Optimized for efficient Promise handling and type safety.
Type Parametersโ
U: Uโ
The type of the transformed error
f:
(e) => U | Promise<U>โ Function to transform the error value (can returnPromise<U>)
Returns:ResultAsync<T, U>โ A new ResultAsync with the original value or the transformed error
Exampleโ
const error = errAsync("network error");
// Synchronous transformation
const enhanced = error.mapErr(e => `Error: ${e}`);
const resolved = await enhanced; // Err("Error: network error")
// Asynchronous transformation
const logged = error.mapErr(async e => {
await logError(e);
return `Logged: ${e}`;
});
const result = await logged; // Err("Logged: network error")
andThen()โ
Chains operations by applying the provided function to the success value. If this resolves to an error result, the error is propagated unchanged.
Optimized for efficient Promise chaining and type safety.
Type Parametersโ
U: Uโ
The type of the success value in the returned ResultAsync
F: Fโ
The type of the error value in the returned ResultAsync
f:
(t) => ResultAsync<U, F>โ Function that takes the success value and returns a new ResultAsync
Returns:ResultAsync<U, E | F>โ A new ResultAsync with combined error types
Exampleโ
const result = okAsync(Promise.resolve(5));
const chained = result.andThen(x =>
x > 0 ? okAsync(Promise.resolve(x * 2)) : errAsync("negative")
);
const resolved = await chained; // Ok(10)
// Chain multiple operations
const pipeline = result
.andThen(x => okAsync(Promise.resolve(x * 2)))
.andThen(x => okAsync(Promise.resolve(x.toString())));
const final = await pipeline; // Ok("10")
unwrapOr()โ
Returns the success value if this resolves to an Ok result, otherwise returns the default value.
Type Parametersโ
A: Aโ
The type of the default value
v:
Aโ Default value to return if this resolves to an error result
Returns:Promise<T | A>โ A Promise that resolves to the success value or the default value
Exampleโ
const success = okAsync(Promise.resolve(42));
const value = await success.unwrapOr(0); // 42
const error = errAsync("failed");
const fallback = await error.unwrapOr(0); // 0
match()โ
Pattern matching function that executes different code paths based on the resolved result state.
Type Parametersโ
A: Aโ
The return type for the success case
B: B = Aโ
The return type for the error case (defaults to A)
ok:
(t) => Aโ Function to execute if this resolves to a success result
err:(e) => Bโ Function to execute if this resolves to an error result
Returns:Promise<A | B>โ A Promise that resolves to the result of executing the appropriate function
Exampleโ
const result = okAsync(Promise.resolve(42));
const message = await result.match(
value => `Success: ${value}`,
error => `Error: ${error}`
); // "Success: 42"
const processed = await result.match(
async value => {
const doubled = value * 2;
await saveToDatabase(doubled);
return doubled;
},
error => 0
); // 84
orElse()โ
Provides an alternative ResultAsync when this resolves to an error. If this resolves to a success result, the original value is returned unchanged.
Type Parametersโ
U: Uโ
The type of the success value in the returned ResultAsync
F: Fโ
The type of the error value in the returned ResultAsync
f:
(e) => ResultAsync<U, F>โ Function that returns a ResultAsync to use as fallback
Returns:ResultAsync<T | U, F>โ A new ResultAsync with the original value or the fallback result
Exampleโ
const result = errAsync("network error");
const fallback = result.orElse(() => okAsync("cached data"));
const resolved = await fallback; // Ok("cached data")
const success = okAsync(42);
const noFallback = success.orElse(() => errAsync("fallback"));
const value = await noFallback; // Ok(42)
then()โ
Implements the PromiseLike interface, allowing ResultAsync to be used with Promise methods like .then(), .catch(), and await.
Provides seamless integration with native Promise APIs and async/await syntax.
Type Parametersโ
TResult1: TResult1 = Result<T, E>โ
The type of the fulfilled result
TResult2: TResult2 = neverโ
The type of the rejected result
onfulfilled?:
Optional callback for when the Promise is fulfilledโ (value) =>TResult1|PromiseLike<TResult1> |null
onrejected?:Optional callback for when the Promise is rejectedโ (reason) =>TResult2|PromiseLike<TResult2> |null
Returns:Promise<TResult1 | TResult2>โ A Promise that resolves to the result of the callbacks
Exampleโ
const result = okAsync(Promise.resolve("hello"));
// Use with .then()
result.then(
res => res.isOk() ? res.value : "error",
error => "promise rejected"
);
// Use with .catch()
result.catch(error => console.error(error));
Implementation ofโ
PromiseLike.then