poll.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * 通用轮询工具:等到断言函数返回 truthy,或超时。
  3. * 用于核心业务 E2E 中"提交生成 → 轮询进度"这种需要等待 LLM/TTS 的场景。
  4. */
  5. export interface PollOptions {
  6. /** 单次间隔 ms,默认 3000 */
  7. intervalMs?: number;
  8. /** 总超时 ms,默认 180000 (3 分钟) */
  9. timeoutMs?: number;
  10. /** 自定义日志前缀 */
  11. label?: string;
  12. }
  13. export async function pollUntil<T>(
  14. fn: () => Promise<T | null | undefined | false>,
  15. opts: PollOptions = {}
  16. ): Promise<T> {
  17. const intervalMs = opts.intervalMs ?? 3000;
  18. const timeoutMs = opts.timeoutMs ?? 180_000;
  19. const label = opts.label ?? 'poll';
  20. const started = Date.now();
  21. // eslint-disable-next-line no-constant-condition
  22. while (true) {
  23. const result = await fn();
  24. if (result) return result;
  25. if (Date.now() - started >= timeoutMs) {
  26. throw new Error(
  27. `[${label}] 轮询超时 (${Math.round(timeoutMs / 1000)}s),最后一次结果为 ${JSON.stringify(result)}`
  28. );
  29. }
  30. await sleep(intervalMs);
  31. }
  32. }
  33. export function sleep(ms: number): Promise<void> {
  34. return new Promise((r) => setTimeout(r, ms));
  35. }