Created
November 4, 2016 09:59
-
-
Save EnoahNetzach/0164ba3ad49b2995daee68f421479522 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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