Skip to content

Instantly share code, notes, and snippets.

@gibatronic
Created April 17, 2020 19:18
Show Gist options
  • Save gibatronic/20c78c846b8072b5a666cd4bdd0a8908 to your computer and use it in GitHub Desktop.
Save gibatronic/20c78c846b8072b5a666cd4bdd0a8908 to your computer and use it in GitHub Desktop.
Cancellable Promises
#!/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()

Cancellable Promises

asciicast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment