Waits until a predicate evaluates to a truthy value or the specified timeout is reached.

Basic usage with a simple condition:

import waitUntil from 'async-wait-until';

const isConditionMet = () => Math.random() > 0.9;

try {
const result = await waitUntil(isConditionMet, { timeout: 5000 });
console.log('Condition met:', result);
} catch (error) {
console.error('Timed out:', error);
}

Usage with custom interval between attempts:

import waitUntil from 'async-wait-until';

const isReady = async () => {
const value = await checkAsyncCondition();
return value > 10;
};

try {
const result = await waitUntil(isReady, { timeout: 10000, intervalBetweenAttempts: 100 });
console.log('Ready:', result);
} catch (error) {
console.error('Timeout reached:', error);
}

Infinite wait with manual timeout handling:

import waitUntil, { WAIT_FOREVER } from 'async-wait-until';

const someCondition = () => Boolean(getConditionValue());

const controller = new AbortController();
setTimeout(() => controller.abort(), 20000); // Cancel after 20 seconds

try {
const result = await waitUntil(someCondition, { timeout: WAIT_FOREVER });
console.log('Condition met:', result);
} catch (error) {
if (controller.signal.aborted) {
console.error('Aborted by the user');
} else {
console.error('Error:', error);
}
}
  • Type Parameters

    Parameters

    • predicate: Predicate<T>

      The function to evaluate repeatedly until it returns a truthy value.

    • Optionaloptions: number | Options

      Either the timeout duration in milliseconds, or an options object for configuring the wait behavior.

    • OptionalintervalBetweenAttempts: number

      The interval (in milliseconds) between predicate evaluations. Ignored if options is an object.

    Returns Promise<T>

    A promise that resolves to the truthy value returned by the predicate, or rejects with a TimeoutError if the timeout is reached.