wait-for.ts 681 B

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