Skip to content

Class: AsyncResult<Value, Err> ​

Defined in: src/result.ts:142

Represents the asynchronous outcome of an operation that can either succeed or fail.

Extends ​

  • Promise<OuterResult<Value, Err>>

Type Parameters ​

Value ​

Value

Err ​

Err

Properties ​

$inferError ​

$inferError: Err

Defined in: src/result.ts:160

Utility getter to infer the error type of the result. Note: this getter does not hold any value, it's only used for type inference.


$inferValue ​

$inferValue: Value

Defined in: src/result.ts:154

Utility getter to infer the value type of the result. Note: this getter does not hold any value, it's only used for type inference.

Accessors ​

isAsyncResult ​

Get Signature ​

get isAsyncResult(): true

Defined in: src/result.ts:169

Utility getter to check if the current instance is an AsyncResult.

Returns ​

true

Methods ​

[iterator]() ​

[iterator](): Generator<{ async: true; error: Err; }, Value, any>

Defined in: src/result.ts:162

Returns ​

Generator<{ async: true; error: Err; }, Value, any>


errorOrNull() ​

errorOrNull(): Promise<ErrorOr<Value, Err, null>>

Defined in: src/result.ts:209

Returns ​

Promise<ErrorOr<Value, Err, null>>

the encapsulated error if the result is a failure, otherwise null.


fold() ​

fold<This, SuccessResult, FailureResult>(this, onSuccess, onFailure): Promise<SuccessResult extends AnyPromise ? Awaited<SuccessResult<SuccessResult>> : SuccessResult | FailureResult extends AnyPromise ? Awaited<FailureResult<FailureResult>> : FailureResult>

Defined in: src/result.ts:331

Returns the result of the onSuccess callback when the result represents success or the result of the onFailure callback when the result represents a failure.

NOTE

Any exceptions that might be thrown inside the callbacks are not caught, so it is your responsibility to handle these exceptions

Type Parameters ​

This ​

This extends AnyAsyncResult

SuccessResult ​

SuccessResult

FailureResult ​

FailureResult

Parameters ​

this ​

This

onSuccess ​

(value) => SuccessResult

callback function to run when the result is successful. The callback can be async as well.

onFailure ​

(error) => FailureResult

callback function to run when the result is a failure. The callback can be async as well.

Returns ​

Promise<SuccessResult extends AnyPromise ? Awaited<SuccessResult<SuccessResult>> : SuccessResult | FailureResult extends AnyPromise ? Awaited<FailureResult<FailureResult>> : FailureResult>

the result of the callback that was executed.

Example ​

folding a result to a response-like object

ts
declare const result: AsyncResult<User, NotFoundError | UserDeactivatedError>;

const response = await result.fold(
  (user) => ({ status: 200, body: user }),
  (error) => {
    switch (error.type) {
      case "not-found":
        return { status: 404, body: "User not found" };
      case "user-deactivated":
        return { status: 403, body: "User is deactivated" };
    }
  }
);

getOrDefault() ​

getOrDefault<Else>(defaultValue): Promise<Value | Else>

Defined in: src/result.ts:245

Retrieves the encapsulated value of the result, or a default value if the result is a failure.

Type Parameters ​

Else ​

Else

Parameters ​

defaultValue ​

The value to return if the result is a failure.

Value | Else

Returns ​

Promise<Value | Else>

The encapsulated value if the result is successful, otherwise the default value.

Examples ​

obtaining the value of a result, or a default value

ts
declare const result: AsyncResult<number, Error>;

const value = await result.getOrDefault(0); // number

using a different type for the default value

ts
declare const result: AsyncResult<number, Error>;

const value = await result.getOrDefault("default"); // number | string

getOrElse() ​

getOrElse<This, Else>(this, onFailure): Promise<InferValue<This> | Else extends AnyPromise ? Awaited<Else<Else>> : Else>

Defined in: src/result.ts:270

Retrieves the value of the result, or transforms the error using the onFailure callback into a value.

Type Parameters ​

This ​

This extends AnyAsyncResult

Else ​

Else

Parameters ​

this ​

This

onFailure ​

(error) => Else

callback function which allows you to transform the error into a value. The callback can be async as well.

Returns ​

Promise<InferValue<This> | Else extends AnyPromise ? Awaited<Else<Else>> : Else>

either the value if the result is successful, or the transformed error.

Examples ​

transforming the error into a value

ts
declare const result: AsyncResult<number, Error>;

const value = await result.getOrElse((error) => 0); // number

using an async callback

ts
const value = await result.getOrElse(async (error) => 0); // number

getOrNull() ​

getOrNull(): Promise<ValueOr<Value, Err, null>>

Defined in: src/result.ts:217

Returns ​

Promise<ValueOr<Value, Err, null>>

the encapsulated value if the result is successful, otherwise null.


getOrThrow() ​

getOrThrow(): Promise<Value>

Defined in: src/result.ts:295

Retrieves the encapsulated value of the result, or throws an error if the result is a failure.

Returns ​

Promise<Value>

The encapsulated value if the result is successful.

Throws ​

the encapsulated error if the result is a failure.

Example ​

obtaining the value of a result, or throwing an error

ts
declare const result: AsyncResult<number, Error>;

const value = await result.getOrThrow(); // number

map() ​

map<This, ReturnType, U>(this, transform): [InferValue<This>] extends [never] ? AsyncResult<never, InferError<This>> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferGeneratorReturn<ReturnType<ReturnType>>, InferError<This> | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<ExtractValue<U>, InferError<This> | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<ExtractValue<U>, InferError<This> | ExtractError<U>> : never

Defined in: src/result.ts:496

Transforms the value of a successful result using the transform callback. The transform callback can also be a generator function or a function that returns other Result or AsyncResult instances, which will be returned as-is (the Error types will be merged). Conceptually, it is similar to Array.flatMap. This map operation will be ignored if the current result represents a failure.

Type Parameters ​

This ​

This extends AnyAsyncResult

ReturnType ​

ReturnType

U ​

U = Awaited<ReturnType>

Parameters ​

this ​

This

transform ​

(value) => ReturnType

callback function to transform the value of the result. The callback can be async or a generator function as well.

Returns ​

[InferValue<This>] extends [never] ? AsyncResult<never, InferError<This>> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferGeneratorReturn<ReturnType<ReturnType>>, InferError<This> | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<ExtractValue<U>, InferError<This> | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<ExtractValue<U>, InferError<This> | ExtractError<U>> : never

a new AsyncResult instance with the transformed value

NOTE

Any exceptions that might be thrown inside the transform callback are not caught, so it is your responsibility to handle these exceptions. Please refer to AsyncResult.mapCatching for a version that catches exceptions and encapsulates them in a failed result.

Examples ​

transforming the value of a result

ts
declare const result: AsyncResult<number, Error>;

const transformed = result.map((value) => value * 2); // AsyncResult<number, Error>

returning a result instance

ts
declare const result: AsyncResult<number, Error>;
declare function multiplyByTwo(value: number): Result<number, Error>;

const transformed = result.map((value) => multiplyByTwo(value)); // AsyncResult<number, Error>

doing an async transformation

ts
declare const result: AsyncResult<number, Error>;

const transformed = result.map(async (value) => value * 2); // AsyncResult<number, Error>

returning an async result instance

ts
declare const result: AsyncResult<number, Error>;
declare function storeValue(value: number): AsyncResult<boolean, Error>;

const transformed = result.map((value) => storeValue(value)); // AsyncResult<boolean, Error>

using a generator function to transform the value

ts
function* doubleValue(value: number) {
  return value * 2;
}

declare const result: AsyncResult<number, Error>;
const transformed = result.map(doubleValue); // AsyncResult<number, Error>

mapCatching() ​

mapCatching<This, ReturnType, ErrorType, U>(this, transformValue, transformError?): [InferValue<This>] extends [never] ? AsyncResult<never, InferError<This>> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferGeneratorReturn<ReturnType<ReturnType>>, ErrorType | InferError<This> | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<ExtractValue<U>, ErrorType | InferError<This> | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<ExtractValue<U>, ErrorType | InferError<This> | ExtractError<U>> : never

Defined in: src/result.ts:529

Like AsyncResult.map it transforms the value of a successful result using the transformValue callback. In addition, it catches any exceptions that might be thrown inside the transformValue callback and encapsulates them in a failed result.

Type Parameters ​

This ​

This extends AnyAsyncResult

ReturnType ​

ReturnType

ErrorType ​

ErrorType = Error

U ​

U = Awaited<ReturnType>

Parameters ​

this ​

This

transformValue ​

(value) => ReturnType

callback function to transform the value of the result. The callback can be async or a generator function as well.

transformError? ​

(error) => ErrorType

callback function to transform any potential caught error while transforming the value.

Returns ​

[InferValue<This>] extends [never] ? AsyncResult<never, InferError<This>> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferGeneratorReturn<ReturnType<ReturnType>>, ErrorType | InferError<This> | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<ExtractValue<U>, ErrorType | InferError<This> | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<ExtractValue<U>, ErrorType | InferError<This> | ExtractError<U>> : never

a new AsyncResult instance with the transformed value


mapError() ​

mapError<This, NewError>(this, transform): AsyncResult<InferValue<This>, NewError>

Defined in: src/result.ts:590

Transforms the encapsulated error of a failed result using the transform callback into a new error. This can be useful for instance to capture similar or related errors and treat them as a single higher-level error type

Type Parameters ​

This ​

This extends AnyAsyncResult

NewError ​

NewError

Parameters ​

this ​

This

transform ​

(error) => NewError

callback function to transform the error of the result.

Returns ​

AsyncResult<InferValue<This>, NewError>

new AsyncResult instance with the transformed error.

Example ​

transforming the error of a result

ts
const result = Result.try(() => fetch("https://example.com"))
 .mapCatching((response) => response.json() as Promise<Data>)
 .mapError((error) => new FetchDataError("Failed to fetch data", { cause: error }));
// AsyncResult<Data, FetchDataError>;

onFailure() ​

onFailure<This>(this, action): AsyncResult<InferValue<This>, InferError<This>>

Defined in: src/result.ts:368

Calls the action callback when the result represents a failure. It is meant to be used for side-effects and the operation does not modify the result itself.

Type Parameters ​

This ​

This extends AnyAsyncResult

Parameters ​

this ​

This

action ​

(error) => void | Promise<void>

callback function to run when the result is a failure. The callback can be async as well.

Returns ​

AsyncResult<InferValue<This>, InferError<This>>

the original instance of the result.

NOTE

Any exceptions that might be thrown inside the action callback are not caught, so it is your responsibility to handle these exceptions

Example ​

adding logging between operations

ts
declare const result: AsyncResult<number, Error>;

result
  .onFailure((error) => console.error("I'm failing!", error))
  .map((value) => value * 2); // proceed with other operations

onSuccess() ​

onSuccess<This>(this, action): AsyncResult<InferValue<This>, InferError<This>>

Defined in: src/result.ts:416

Calls the action callback when the result represents a success. It is meant to be used for side-effects and the operation does not modify the result itself.

Type Parameters ​

This ​

This extends AnyAsyncResult

Parameters ​

this ​

This

action ​

(value) => void | Promise<void>

callback function to run when the result is successful. The callback can be async as well.

Returns ​

AsyncResult<InferValue<This>, InferError<This>>

the original instance of the result.

NOTE

Any exceptions that might be thrown inside the action callback are not caught, so it is your responsibility to handle these exceptions

Examples ​

adding logging between operations

ts
declare const result: AsyncResult<number, Error>;

result
  .onSuccess((value) => console.log("I'm a success!", value))
  .map((value) => value * 2); // proceed with other operations

using an async callback

ts
declare const result: AsyncResultResult<number, Error>;

const asyncResult = await result.onSuccess(async (value) => someAsyncOperation(value));

recover() ​

recover<This, ReturnType, U>(this, onFailure): [InferError<This>] extends [never] ? AsyncResult<InferValue<This>, never> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferValue<This> | InferGeneratorReturn<ReturnType<ReturnType>>, InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ExtractError<U>> : never : ReturnType extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ExtractError<U>> : never

Defined in: src/result.ts:638

Transforms a failed result using the onFailure callback into a successful result. Useful for falling back to other scenarios when a previous operation fails. The onFailure callback can also be a generator function or a function that returns other Result or AsyncResult instances, which will be returned as-is (much like Array.flatMap). After a recovery, logically, the result can only be a success. Therefore, the error type is set to never, unless the onFailure callback returns a result-instance with another error type.

Type Parameters ​

This ​

This extends AnyAsyncResult

ReturnType ​

ReturnType

U ​

U = Awaited<ReturnType>

Parameters ​

this ​

This

onFailure ​

(error) => ReturnType

callback function to transform the error of the result. The callback can be async or a generator function as well.

Returns ​

[InferError<This>] extends [never] ? AsyncResult<InferValue<This>, never> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferValue<This> | InferGeneratorReturn<ReturnType<ReturnType>>, InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ExtractError<U>> : never : ReturnType extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ExtractError<U>> : never

a new successful AsyncResult instance when the result represents a failure, or the original instance if it represents a success.

NOTE

Any exceptions that might be thrown inside the onFailure callback are not caught, so it is your responsibility to handle these exceptions. Please refer to AsyncResult.recoverCatching for a version that catches exceptions and encapsulates them in a failed result.

Example ​

transforming the error into a value Note: Since we recover after trying to persist in the database, we can assume that the DbError has been taken care of and therefore it has been removed from the final result.

ts
declare function persistInDB(item: Item): AsyncResult<Item, DbError>;
declare function persistLocally(item: Item): AsyncResult<Item, IOError>;

persistInDB(item).recover(() => persistLocally(item)); // AsyncResult<Item, IOError>

recoverCatching() ​

recoverCatching<This, ReturnType, ErrorType, U>(this, onFailure, transformError?): [InferError<This>] extends [never] ? AsyncResult<InferValue<This>, never> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferValue<This> | InferGeneratorReturn<ReturnType<ReturnType>>, ErrorType | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ErrorType | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ErrorType | ExtractError<U>> : never

Defined in: src/result.ts:677

Like AsyncResult.recover it transforms a failed result using the onFailure callback into a successful result. In addition, it catches any exceptions that might be thrown inside the onFailure callback and encapsulates them in a failed result.

Type Parameters ​

This ​

This extends AnyAsyncResult

ReturnType ​

ReturnType

ErrorType ​

ErrorType = Error

U ​

U = Awaited<ReturnType>

Parameters ​

this ​

This

onFailure ​

(error) => ReturnType

callback function to transform the error of the result. The callback can be async or a generator function as well.

transformError? ​

(error) => ErrorType

callback function to transform any potential caught error while recovering the result.

Returns ​

[InferError<This>] extends [never] ? AsyncResult<InferValue<This>, never> : [ReturnType] extends [Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>] ? AsyncResult<InferValue<This> | InferGeneratorReturn<ReturnType<ReturnType>>, ErrorType | InferGeneratorError<ReturnType<ReturnType>>> : [ReturnType] extends [Promise<PValue>] ? PValue extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ErrorType | ExtractError<U>> : never : ReturnType extends U ? AsyncResult<InferValue<This> | ExtractValue<U>, ErrorType | ExtractError<U>> : never

a new successful AsyncResult instance when the result represents a failure, or the original instance if it represents a success.


toString() ​

toString(): string

Defined in: src/result.ts:716

Print-friendly representation of the AsyncResult instance.

Returns ​

string


toTuple() ​

toTuple<This, V, E>(this): Promise<[E] extends [never] ? [V, never] : [V] extends [never] ? [never, E] : [V, null] | [null, E]>

Defined in: src/result.ts:193

Type Parameters ​

This ​

This extends AnyAsyncResult

V ​

V = InferValue<This>

E ​

E = InferError<This>

Parameters ​

this ​

This

Returns ​

Promise<[E] extends [never] ? [V, never] : [V] extends [never] ? [never, E] : [V, null] | [null, E]>

the result in a tuple format where the first element is the value and the second element is the error. If the result is successful, the error will be null. If the result is a failure, the value will be null.

This method is especially useful when you want to destructure the result into a tuple and use TypeScript's narrowing capabilities.

Example ​

ts
declare const result: AsyncResult<number, ErrorA>;

const [value, error] = await result.toTuple();

if (error) {
  // error is ErrorA
  return;
}

// value must be a number