happy-rusty
    Preparing search index...

    Function tryAsyncResult

    • Executes an async operation and captures any rejection as an Err. If the operation succeeds, returns Ok with the resolved value.

      This overload accepts a Promise or PromiseLike object directly. Use this to convert Promise-based error handling to Result-based handling.

      Type Parameters

      • T

        The type of the value that the promise resolves to.

      • E = Error

        The type of the error that may be rejected, defaults to Error.

      Parameters

      • task: PromiseLike<T>

        A promise or promise-like object to await.

      Returns AsyncResult<Awaited<T>, E>

      A promise that resolves to Ok<T> if successful, or Err<E> if rejected.

      1.7.0

      // Fetch data safely
      const result = await tryAsyncResult(fetch('/api/data'));
      result.inspect(response => console.log('Status:', response.status))
      .inspectErr(err => console.error('Fetch failed:', err));
      // With typed error
      const result = await tryAsyncResult<User, ApiError>(api.getUser(id));
    • Executes a function and captures any thrown exception or rejection as an Err. If the function succeeds, returns Ok with the result.

      This overload accepts a function that may return a sync value or a Promise. It captures both synchronous exceptions (thrown before the Promise is created) and asynchronous rejections.

      Similar to Promise.try, you can pass arguments to the function.

      Type Parameters

      • T

        The type of the value returned or resolved by the function.

      • E = Error

        The type of the error that may be thrown or rejected, defaults to Error.

      • Args extends unknown[] = []

        The types of the arguments to pass to the function.

      Parameters

      • task: (...args: Args) => T | PromiseLike<T>

        A function that returns a value or promise-like object.

      • ...args: Args

        Arguments to pass to the function.

      Returns AsyncResult<Awaited<T>, E>

      A promise that resolves to Ok<T> if successful, or Err<E> if thrown or rejected.

      1.7.0

      // Function with arguments
      const result = await tryAsyncResult(fetch, '/api/data');
      // Function can return sync or async value (like Promise.try)
      const result = await tryAsyncResult((id) => {
      if (cache.has(id)) return cache.get(id); // sync return
      return fetchFromServer(id); // async return
      }, 'user-123');
      // Inline async function
      const result = await tryAsyncResult(async () => {
      const response = await fetch('/api');
      return response.json();
      });
      // With custom error type
      const result = await tryAsyncResult<Config, ConfigError, [string]>(loadConfig, 'app.json');