Skip to content

Instantly share code, notes, and snippets.

@rdm
Created January 16, 2019 01:25
Show Gist options
  • Save rdm/7aa51c2af32c695314886366391ce76f to your computer and use it in GitHub Desktop.
Save rdm/7aa51c2af32c695314886366391ce76f to your computer and use it in GitHub Desktop.
/*
* testing involving real time is an integration test - high value, high cost
* these next two routines represent that interface
*/
const msDeadline= ms=> {
console.log('msDeadline',ms);
const deadline= ms+new Date().getTime();
return ()=>deadline < new Date().getTime();
};
const msDelay= ms=> {
console.log('msDelay',ms);
return new Promise(resolve => setTimeout(resolve, ms));
}
/*
* you'll want something different:
*/
const tryToConnect= ()=> {
const n= Math.random();
console.log('tryToConnect',n);
return 0.1 > n;
}
/*
* Try to connect every 250ms for two seconds,
* and return me a Promise. If you connect,
* resolve the Promise with true, if you fail until
* timeout, resolve it with false.
*/
const promiseToConnect= async ()=> {
const pastDeadline= msDeadline(2000);
do {
if (tryToConnect()) return true;
await msDelay(250);
} while (!pastDeadline());
return false;
}
/*
* test jig
*/
let p= promiseToConnect();
p.then((ok)=>console.log('done', ok));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment