async-spec-helpers.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. async function conditionPromise(
  2. condition,
  3. description = 'anonymous condition'
  4. ) {
  5. const startTime = Date.now();
  6. while (true) {
  7. await timeoutPromise(100);
  8. // if condition is sync
  9. if (condition.constructor.name !== 'AsyncFunction' && condition()) {
  10. return;
  11. }
  12. // if condition is async
  13. else if (await condition()) {
  14. return;
  15. }
  16. if (Date.now() - startTime > 5000) {
  17. throw new Error('Timed out waiting on ' + description);
  18. }
  19. }
  20. }
  21. function timeoutPromise(timeout) {
  22. return new Promise(resolve => {
  23. global.setTimeout(resolve, timeout);
  24. });
  25. }
  26. function emitterEventPromise(emitter, event, timeout = 15000) {
  27. return new Promise((resolve, reject) => {
  28. const timeoutHandle = setTimeout(() => {
  29. reject(new Error(`Timed out waiting for '${event}' event`));
  30. }, timeout);
  31. emitter.once(event, () => {
  32. clearTimeout(timeoutHandle);
  33. resolve();
  34. });
  35. });
  36. }
  37. exports.conditionPromise = conditionPromise;
  38. exports.emitterEventPromise = emitterEventPromise;
  39. exports.timeoutPromise = timeoutPromise;