happy-rusty
    Preparing search index...

    Function tryAsyncOption

    • Executes an async operation and returns Some with the resolved value if successful, or None if it rejects.

      This overload accepts a Promise or PromiseLike object directly. Use this when you already have a Promise and only care about success/failure, not the error details.

      Type Parameters

      • T

        The type of the value that the promise resolves to.

      Parameters

      • task: PromiseLike<T>

        A promise or promise-like object to await.

      Returns AsyncOption<Awaited<T>>

      A promise that resolves to Some<T> if successful, or None if rejected.

      1.7.0

      // Fetch data, ignore error details
      const data = await tryAsyncOption(fetch('/api/data').then(r => r.json()));
      console.log(data.unwrapOr(defaultData));
      // With existing promise
      const fileContent = await tryAsyncOption(fs.promises.readFile('config.json', 'utf-8'));
    • Executes a function and returns Some with the result if successful, or None if it throws or rejects.

      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.

      • 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 AsyncOption<Awaited<T>>

      A promise that resolves to Some<T> if successful, or None if thrown or rejected.

      1.7.0

      // Function with arguments
      const result = await tryAsyncOption(fetch, '/api/data');
      // Function can return sync or async value (like Promise.try)
      const result = await tryAsyncOption((id) => {
      if (cache.has(id)) return cache.get(id); // sync return
      return fetchFromServer(id); // async return
      }, 'user-123');
      // Inline async function
      const data = await tryAsyncOption(async () => {
      const response = await fetch('/api');
      return response.json();
      });