Logos DX
    Preparing search index...

    Function withTimeout

    • Wraps an async function with a timeout mechanism. If the function doesn't complete within the specified timeout, it will reject with a TimeoutError.

      Type Parameters

      • T extends Func

        The type of the function being wrapped

      Parameters

      • fn: T

        The async function to wrap with timeout functionality

      • opts: WithTimeoutOptions

        Configuration options

        • OptionalabortController?: AbortController

          Abort controller to cancel the operation

        • OptionalonError?: (error: Error, didTimeout: boolean) => void

          Capture errors

        • OptionalonTimeout?: (error: TimeoutError) => void

          On timeout callback

        • Optionalthrows?: boolean

          Rethrow errors

        • timeout: number

          Timeout in milliseconds after which the function will be rejected

      Returns T

      A new async function with the same signature as the original, but with timeout behavior

      When the function execution exceeds the specified timeout

      // Basic usage with a fetch request
      const abortController = new AbortController();
      const fetchWithTimeout = withTimeout(fetch, { timeout: 5000, abortController });

      try {
      const response = await fetchWithTimeout('https://api.example.com/data', { signal: abortController.signal });
      console.log('Request completed within 5 seconds');
      } catch (error) {
      if (error instanceof TimeoutError) {
      console.log('Request timed out after 5 seconds');
      } else {
      console.log('Request failed:', error.message);
      }
      }
      // Wrapping a custom async function
      async function processData(data: string[]): Promise<string> {
      // Simulate slow processing
      await new Promise(resolve => setTimeout(resolve, 3000));
      return data.join(', ');
      }

      const abortController = new AbortController();
      const processWithTimeout = withTimeout(processData, { timeout: 2000, abortController });

      const [result, error] = await attempt(() =>
      processWithTimeout(['a', 'b', 'c'], { signal: abortController.signal })
      );

      if (error) {
      console.log('Processing timed out or failed');
      } else {
      console.log('Result:', result);
      }
      // Using with database operations
      const queryWithTimeout = withTimeout(
      async (query: string) => database.execute(query)
      { timeout: 10000 }
      );

      try {
      const users = await queryWithTimeout('SELECT * FROM users');
      return users;
      } catch (error) {
      if (isTimeoutError(error)) {
      throw new Error('Database query timed out after 10 seconds');
      }
      throw error;
      }