Eventually Assertion Helper

Poll an async predicate until it succeeds or times out, with abort support and the last error preserved as the cause.

TypescriptResilience

Code

typescriptsnippet
39 lines
export interface EventuallyOptions {
  timeoutMs?: number;
  intervalMs?: number;
  signal?: AbortSignal;
}

export async function eventually<T>(
  predicate: () => T | Promise<T>,
  options: EventuallyOptions = {},
): Promise<T> {
  const { timeoutMs = 2000, intervalMs = 50, signal } = options;
  if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
    throw new RangeError("timeoutMs must be a non-negative finite number");
  }
  if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
    throw new RangeError("intervalMs must be a positive finite number");
  }
  const deadline = Date.now() + timeoutMs;
  let lastError: unknown;
  while (true) {
    if (signal?.aborted) {
      const aborted = new Error("eventually aborted");
      aborted.name = "AbortError";
      throw aborted;
    }
    try {
      const value = await predicate();
      if (value) return value;
    } catch (error) {
      lastError = error;
    }
    if (Date.now() >= deadline) {
      const message = "eventually timed out after " + timeoutMs + "ms";
      throw lastError ? new Error(message, { cause: lastError }) : new Error(message);
    }
    const wait = Math.min(intervalMs, Math.max(0, deadline - Date.now()));
    await new Promise<void>((resolve) => setTimeout(resolve, wait));
  }
}

How it works

Count the function eventually as the entire surface area of Eventually Assertion Helper.

The one repetition in this snippet is the loop while (true). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the RangeError: bad state stops the flow there instead of continuing.

Points of care

  • The guard value short-circuits the flow with an early return when its condition holds.

Using it

eventually is what another module would consume; nothing else here is load-bearing for callers.

Key statements

await new Promise<void>((resolve) => setTimeout(resolve, wait));
throw lastError ? new Error(message, { cause: lastError }) : new Error(message);
throw new RangeError("timeoutMs must be a non-negative finite number");

Interactive Tools for This Topic

FAQ

Does the code validate its input?
The code throws `RangeError` — the guard `value` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `eventually` at load time.