Function asyncWithTimeout

  • Executes an async task with a timeout.

    Type Parameters

    • T

      The type of the value that the Promise resolves to.

    Parameters

    • timeout: number

      The timeout in milliseconds.

    • task: (() => Promise<T>)

      The async task to execute.

        • (): Promise<T>
        • Returns Promise<T>

    Returns Promise<T>

    A promise that resolves with the task's result or rejects with an error.

    Throws

    If the Promise does not resolve within the specified time, an Error is thrown with a message indicating the timeout.

    Example

    // Example 1: Resolving a promise within the timeout
    asyncWithTimeout(5000, async () => {
    await new Promise((resolve) => setTimeout(resolve, 2000))
    return 'Task completed within timeout'
    })
    .then((result) => console.log(result))
    .catch((error) => console.error(error))
    // Example 2: Rejecting a promise due to timeout
    asyncWithTimeout(2000, async () => {
    await new Promise((resolve) => setTimeout(resolve, 5000))
    return 'This should not be returned'
    })
    .then((result) => console.log(result))
    .catch((error) => console.error(error))

Generated using TypeDoc