Skip to content

Instantly share code, notes, and snippets.

@EnoahNetzach
Created November 4, 2016 09:59
Show Gist options
  • Save EnoahNetzach/0164ba3ad49b2995daee68f421479522 to your computer and use it in GitHub Desktop.
Save EnoahNetzach/0164ba3ad49b2995daee68f421479522 to your computer and use it in GitHub Desktop.
const raceAgainst = (fn, timeout) => new Promise((resolve, reject) => {
const timer = setTimeout(() => {
resetTimer()
resolve(false)
}, timeout)
const resetTimer = () => timer && clearTimeout(timer)
const asyncFn = async () => {
try {
await fn()
resolve(true)
} catch (error) {
reject(error)
} finally {
resetTimer()
}
}
asyncFn()
})
const asyncSideEffect = ok => async () => {
await new Promise((resolve, reject) => setTimeout(ok ? resolve : reject, 200))
return 42
}
await raceAgainst(asyncSideEffect(true), 100)
.then(x => console.log(x ? 'in time' : 'too late'))
.catch(() => console.error('error'))
await raceAgainst(asyncSideEffect(true), 300)
.then(x => console.log(x ? 'in time' : 'too late'))
.catch(() => console.error('error'))
await raceAgainst(asyncSideEffect(false), 100)
.then(x => console.log(x ? 'in time' : 'too late'))
.catch(() => console.error('error'))
await raceAgainst(asyncSideEffect(false), 300)
.then(x => console.log(x ? 'in time' : 'too late'))
.catch(() => console.error('error'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment