Skip to content

Instantly share code, notes, and snippets.

@rdm
Created January 16, 2019 16:30
Show Gist options
  • Save rdm/0318e4c37a40c24b03116b4a3afff7f8 to your computer and use it in GitHub Desktop.
Save rdm/0318e4c37a40c24b03116b4a3afff7f8 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));
}
/*
* here we use the type pun that non-zero integers are true
* but you'll want something different:
*/
let attemptCount= 0;
const tryToConnect= async ()=> {
const attempt= ++attemptCount;
const s5= Math.sqrt(5);
const delay= Math.pow((1+s5),20*Math.random())%s5;
const success= 0.5<Math.random();
console.log('tryToConnect',attempt,delay,success);
await msDelay(delay);
if (success) {
return attempt;
} else {
throw new Error();
}
}
/*
* 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);
let attempts= [];
do {
const pause= msDelay(250).then(()=>false);
attempts.push(tryToConnect());
try {
const fileNumber= await Promise.race([pause].concat(attempts));
if (fileNumber) return fileNumber;
} catch (e) {
await pause;
}
} while (!pastDeadline());
return false;
}
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