Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created April 23, 2018 08:02
Show Gist options
  • Save wesleybliss/f57333fae07b74ed2f3062f68f482956 to your computer and use it in GitHub Desktop.
Save wesleybliss/f57333fae07b74ed2f3062f68f482956 to your computer and use it in GitHub Desktop.
Attempt a function waiting for a condition a number of times before failing
const attempt = (fn, delay, max, count = 0) => {
let pendingResolve = null
let pendingReject = null
const pendingPromise = new Promise((resolve, reject) => {
pendingResolve = resolve
pendingReject = reject
})
const condition = fn()
if (condition === true) {
pendingResolve(condition)
}
else if (count >= max && condition !== true) {
pendingReject(condition)
}
else {
setTimeout(() => {
pendingResolve(attempt(fn, delay, max, (count + 1)))
}, delay)
}
return pendingPromise
}
// Example Usage:
let condition = false
const isConditionTrue = () => condition === true
const run = async () => {
const attempts = 3
try {
await attempt(isConditionTrue, 1000, attempts)
console.error(`condition was met in ${attempts}`)
}
catch (e) {
console.error(`condition failed to be met within ${attempts} attempts`)
}
}
// This will fail after 3 attempts
run()
// This will not fail, b/c the condition changes to `true` half way through the attempts
setTimeout(() => { condition = true }, 1500)
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment