Guest User

Untitled

a guest
Jan 16th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. /*
  2. * testing involving real time is an integration test - high value, high cost
  3. * these next two routines represent that interface
  4. */
  5. const msDeadline= ms=> {
  6. console.log('msDeadline',ms);
  7. const deadline= ms+new Date().getTime();
  8. return ()=>deadline < new Date().getTime();
  9. };
  10.  
  11. const msDelay= ms=> {
  12. console.log('msDelay',ms);
  13. return new Promise(resolve => setTimeout(resolve, ms));
  14. }
  15.  
  16. /*
  17. * you'll want something different:
  18. */
  19. const tryToConnect= ()=> {
  20. const n= Math.random();
  21. console.log('tryToConnect',n);
  22. return 0.1 > n;
  23. }
  24.  
  25. /*
  26. * Try to connect every 250ms for two seconds,
  27. * and return me a Promise. If you connect,
  28. * resolve the Promise with true, if you fail until
  29. * timeout, resolve it with false.
  30. */
  31. const promiseToConnect= async ()=> {
  32. const pastDeadline= msDeadline(2000);
  33. do {
  34. if (tryToConnect()) return true;
  35. await msDelay(250);
  36. } while (!pastDeadline());
  37. return false;
  38. }
  39.  
  40. /*
  41. * test jig
  42. */
  43. let p= promiseToConnect();
  44. p.then((ok)=>console.log('done', ok));
Add Comment
Please, Sign In to add comment