• Attach a timeout to any promise, if the timeout resolves first ignore the original promise and throw an error

    Type Parameters

    • Value

    Parameters

    • promise: Promise<Value>

      The promise to attach a timeout to

    • options: { controller?: AbortController; ms: number }

      The options to use

      • Optionalcontroller?: AbortController

        An AbortController to abort the original promise

      • ms: number

        The number of milliseconds to wait before timing out

    Returns Promise<Value>

    The result of the promise

    TimeoutError If the timeout resolves first

    try {
    let result = await timeout(
    fetch("https://example.com"),
    { ms: 100 }
    );
    } catch (error) {
    if (error instanceof TimeoutError) {
    // Handle timeout
    }
    }
    try {
    let controller = new AbortController();
    let result = await timeout(
    fetch("https://example.com", { signal: controller.signal }),
    { ms: 100, controller }
    );
    } catch (error) {
    if (error instanceof TimeoutError) {
    // Handle timeout
    }
    }