File size: 699 Bytes
1778c9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/**
* Polls a predicate function until it returns a truthy value or times out.
* @param predicate - Function to evaluate. Should return a value or a Promise.
* @param options - Polling options.
* @returns The truthy value returned by predicate, or undefined if timed out.
*/
export async function poll<T>(
predicate: () => T | Promise<T>,
options: { interval?: number; maxAttempts?: number } = {}
): Promise<T | undefined> {
const { interval = 10, maxAttempts = 200 } = options;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const result = await predicate();
if (result) return result;
await new Promise(resolve => setTimeout(resolve, interval));
}
return undefined;
}
|