Created
April 17, 2020 19:18
-
-
Save gibatronic/20c78c846b8072b5a666cd4bdd0a8908 to your computer and use it in GitHub Desktop.
Cancellable Promises
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
#!/usr/bin/env node | |
class CancelError extends Error { | |
constructor(message) { | |
super(message) | |
this.name = 'CancelError' | |
} | |
} | |
function random(minimum, maximum) { | |
return minimum + Math.floor(Math.random() * (maximum - minimum + 1)) | |
} | |
function sleep(signal) { | |
return new Promise((resolve, reject) => { | |
const timeout = setTimeout( | |
resolve, | |
random(250, 750), | |
random(0, 1) ? 'z' : 'Z' | |
) | |
signal.cancel = () => { | |
clearTimeout(timeout) | |
reject(new CancelError('\\(´O`)/')) | |
} | |
}) | |
} | |
async function main() { | |
const signal = { | |
cancel: () => {} | |
} | |
setTimeout( | |
() => signal.cancel(), | |
random(2500, 7500) | |
) | |
try { | |
while (true) { | |
console.log(await sleep(signal)) | |
} | |
} catch(exception) { | |
if (exception instanceof CancelError) { | |
console.log(exception.message) | |
return | |
} | |
throw exception | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment