@bnidev/js-utils
    Preparing search index...

    Function timeoutAsyncFn

    • Wraps a promise with a timeout. If the promise does not resolve within the specified time, it rejects with a 'Timeout' error.

      Type Parameters

      • T

      Parameters

      • promise: Promise<T>

        The promise to wrap.

      • ms: number

        The timeout duration in milliseconds.

      Returns Promise<T>

      A new promise that resolves or rejects based on the original promise and the timeout.

      This utility is useful for ensuring that asynchronous operations do not hang indefinitely.

      // ES Module
      import { timeoutAsyncFn } from '@bnidev/js-utils'

      // CommonJS
      const { timeoutAsyncFn } = require('@bnidev/js-utils')
      // Wrap a fetch request with a timeout
      const fetchWithTimeout = timeoutAsyncFn(fetch('https://api.example.com/data'), 5000)
      fetchWithTimeout
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error))
      // If the fetch does not complete within 5 seconds, it will reject with 'Timeout'