Skip to content

Instantly share code, notes, and snippets.

@jczaplew
Created June 4, 2018 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jczaplew/a312a7c7728d34115068b260574ceda9 to your computer and use it in GitHub Desktop.
Save jczaplew/a312a7c7728d34115068b260574ceda9 to your computer and use it in GitHub Desktop.
Cancelable async
class Cancelable {
constructor() {
this.canceled = false
}
count(val) {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve(val*val)
}, 1000)
})
}
async start() {
for (const each of [1,2,3,4,5]) {
if (this.canceled) {
break
}
try {
let answer = await this.count(each)
console.log(each, answer)
} catch(e) {
console.log('Could not compute')
}
}
console.log('done')
}
cancel() {
this.canceled = true
}
}
/*
let foo = new Cancelable()
foo.start()
setTimeout(() => {
foo.cancel()
}, 5000)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment