wait-for.ts 759 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { debugConsole } from '@/utils/debugging'
  2. export function waitFor<T>(
  3. testFunction: () => T,
  4. timeout: number,
  5. pollInterval = 500
  6. ): Promise<T> {
  7. const iterationLimit = Math.floor(timeout / pollInterval)
  8. let iterations = 0
  9. return new Promise<T>((resolve, reject) => {
  10. const tryIteration = () => {
  11. if (iterations > iterationLimit) {
  12. const err = new Error(
  13. `waiting too long, ${JSON.stringify({ timeout, pollInterval })}`
  14. )
  15. debugConsole.error(err)
  16. reject(err)
  17. return
  18. }
  19. iterations += 1
  20. const result = testFunction()
  21. if (result) {
  22. resolve(result)
  23. return
  24. }
  25. setTimeout(tryIteration, pollInterval)
  26. }
  27. tryIteration()
  28. })
  29. }