Skip to content

Instantly share code, notes, and snippets.

@midnqp
Created November 10, 2022 16:34
Show Gist options
  • Save midnqp/14a1924d7434768969131b6aa2a28c13 to your computer and use it in GitHub Desktop.
Save midnqp/14a1924d7434768969131b6aa2a28c13 to your computer and use it in GitHub Desktop.
/**
* Runs the `idempotentFn` for ~4400ms, in an interval
* of 50ms - to satisfy `testFn`. If unsatisfied, throws Error(`msg`).
*
* @param idempotentFn - a function that can be executed ∞ times
* without a side-effect.
* @param testFn - throw if unsatisfied; if no throw, then return perfectly ✓!
* @param msg - error message to throw if no luck at all
*/
async function waitAndSee (idempotentFn, testFn, msg) {
let countMs = 0
const stepMs = 50
const totalMs = 4400 - stepMs
const sleep = ms => new Promise(r => setTimeout(r, ms))
function log (str, lineEnd = '\n', tab = ' '.repeat(6)) {
if (typeof str === 'object') str = util.inspect(str)
process.stdout.write(tab + (str) + lineEnd)
}
const logEnd = ms => log('] ' + ms + 'ms', '\n', '')
log('[', '')
while (countMs < totalMs) {
const start = new Date()
const retval = await idempotentFn()
let okay = false
try {
// @ts-ignore
await testFn(retval)
okay = true
} catch (err) {
okay = false
}
const ms = new Date().getTime() - start.getTime()
countMs += ms
if (okay) {
logEnd(countMs)
return retval
}
log('-', '', '')
countMs += stepMs
await sleep(stepMs)
}
logEnd(countMs)
throw Error(msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment