Skip to content

Instantly share code, notes, and snippets.

@dangh
Last active October 8, 2020 12:01
Show Gist options
  • Save dangh/b8968cee5d33fdda15f59b605ac1c5ec to your computer and use it in GitHub Desktop.
Save dangh/b8968cee5d33fdda15f59b605ac1c5ec to your computer and use it in GitHub Desktop.
function abortableAsync(generator) {
return ({
[generator.name](...args) {
let halt = false;
try {
return () => { halt = true; };
} finally {
(async() => {
let g = generator.call(this, ...args);
let value, done, err;
while(!done && !halt) {
if(err) {
({ value, done } = g.throw(err));
err = null;
} else {
({ value, done } = g.next(value));
}
if(value instanceof Promise) value = await value.catch(e => { err = e; });
}
})();
}
}
})[generator.name];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment