Created
June 4, 2018 20:21
-
-
Save jczaplew/a312a7c7728d34115068b260574ceda9 to your computer and use it in GitHub Desktop.
Cancelable async
This file contains 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
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