Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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