typesafe-ts API Documentation - v1.2.0
    Preparing search index...

    Class AsyncResult<ResultType, ErrorType>

    An awaitable wrapper for Result that enables immediate method chaining on async operations. AsyncResult implements PromiseLike and provides Result transformation methods like map, and_then, and or_else. The AsyncResult must be awaited to inspect the final result with is_ok() or is_error().

    // Chain operations and await the final result in one expression
    const finalResult = await result.try_async(() => fetchUser("123"))
    .map(user => user.name.toUpperCase())
    .and_then(name => name ? result.ok(name) : result.error(new Error("Empty name")))
    .or_else(() => result.ok("Unknown"));

    Type Parameters

    • ResultType

      The type of the ok value

    • ErrorType extends Error

      The type of the error (must extend Error)

    Implements

    Index

    Constructors

    • Creates a new AsyncResult from a Promise that resolves to a Result.

      While result.try_async() is the preferred way to create AsyncResult instances, the constructor is useful when you have an async function that already returns a Promise<Result>. Wrapping it with new AsyncResult() provides access to the chaining API without requiring await and without "coloring" your function as async. This is particularly beneficial in contexts where await isn't allowed, such as top-level code or in component logic of some frontend frameworks.

      Type Parameters

      • ResultType
      • ErrorType extends Error

      Parameters

      Returns AsyncResult<ResultType, ErrorType>

      // Async function that returns Promise<Result>
      async function fetchUserData(id: string): Promise<Result<User, Error>> {
      return result.try_async(() => fetch(`/api/users/${id}`))
      .then(response => response.json());
      }

      // Without AsyncResult constructor: requires await, makes function async
      async function processUserAsync(id: string): Promise<Result<string, Error>> {
      const userData = await fetchUserData(id);
      return userData.map(user => user.name.toUpperCase());
      }

      // With AsyncResult constructor: no await needed, function stays sync
      function processUserSync(id: string): AsyncResult<string, Error> {
      return new AsyncResult(fetchUserData(id))
      .map(user => user.name.toUpperCase());
      }

      // Both usage patterns work the same way:
      const result1 = await processUserAsync("123");
      const result2 = await processUserSync("123");

    Accessors

    Methods

    • PromiseLike implementation equivalent to Promise.then. Allows AsyncResult to be awaited.

      Type Parameters

      • TResult1 = Result<ResultType, ErrorType>

        The type returned when the promise resolves

      • TResult2 = never

        The type returned when the promise rejects

      Parameters

      • Optionalonfulfilled:
            | null
            | (
                (
                    value: Result<ResultType, ErrorType>,
                ) => TResult1 | PromiseLike<TResult1>
            )

        Callback executed when the AsyncResult resolves to a Result

      • Optionalonrejected: null | ((reason: unknown) => TResult2 | PromiseLike<TResult2>)

        Callback executed when the AsyncResult rejects

      Returns PromiseLike<TResult1 | TResult2>

      A PromiseLike that resolves to the result of the executed callback

    • Returns the contained value if Ok, otherwise returns the provided default value.

      Parameters

      • value_if_error: ResultType

        The value to return if the Result contains an error

      Returns Promise<ResultType>

      A Promise resolving to the contained value or the default value

    • Access the contained error if this result is an error. Otherwise returns the provided default error.

      Parameters

      • error_if_ok: ErrorType

        The error to return if the Result contains a value

      Returns Promise<ErrorType>

      A Promise resolving to the contained error or the default error

    • Executes an async function with the contained value if Ok, and wraps the result in a Result. If this AsyncResult is Error, the function is not called and the error is propagated. If the async function throws or rejects, the error is caught and wrapped in a TryAsyncError with detailed debugging information.

      Type Parameters

      • NewResultType

        The type of the value returned by the async function

      Parameters

      Returns AsyncResult<NewResultType, TryAsyncError | ErrorType>

      A new AsyncResult containing the result of the async function or a union of the original error and TryAsyncError

      // Chain async operations with rich error information
      const userData = await result.try_async(() => fetch('/api/user/123'))
      .try_async(response => response.json()) // Creates TryAsyncError if JSON parsing fails
      .map(user => user.name)
      .match(
      name => console.log(`User: ${name}`),
      error => {
      if (error instanceof TryAsyncError) {
      console.log(`Operation "${error.operation}" failed`);
      console.log(`Original error:`, error.originalError);
      }
      }
      );
    • Executes an async function with the contained value if Ok, and wraps the result in a Result. If this AsyncResult is Error, the function is not called and the error is propagated. If the async function throws or rejects, the error is caught and passed to the provided error mapper.

      Type Parameters

      • NewResultType

        The type of the value returned by the async function

      • NewErrorType extends Error

        The type of the error returned by the error mapper

      Parameters

      • fn: (value: ResultType) => Promise<NewResultType>

        Async function that takes the Ok value and returns a Promise

      • errorMapper: (error: unknown) => NewErrorType

        Function that maps the caught error to a specific error type

      Returns AsyncResult<NewResultType, ErrorType | NewErrorType>

      A new AsyncResult containing the result of the async function or a union of the original error and mapped error

      // Chain async operations with custom error mapping
      const userData = await result.try_async(() => fetch('/api/user/123'))
      .try_async(
      response => response.json(),
      error => new JsonParseError(`Failed to parse response: ${error}`)
      )
      .map(user => user.name);
    • Async iterator support. Yields the contained value if Ok, nothing if Error.

      Returns AsyncGenerator<ResultType, void, unknown>

      An async generator that yields the value if Ok, otherwise yields nothing

      // Iterate over successful values
      for await (const value of result.try_async(() => fetchUser("123"))) {
      console.log(value.name); // Only executes if fetch succeeds
      }

      // Collect successful values from multiple async operations
      const users = [];
      for await (const user of result.try_async(() => fetchUser("456"))) {
      users.push(user);
      }