Skip to content

Instantly share code, notes, and snippets.

@alekstar79
Last active May 24, 2024 16:26
Show Gist options
  • Select an option

  • Save alekstar79/df1fc470dc075c48d67e30eccb3f6d78 to your computer and use it in GitHub Desktop.

Select an option

Save alekstar79/df1fc470dc075c48d67e30eccb3f6d78 to your computer and use it in GitHub Desktop.
Сancelable promise
const noop = () => {}
export class Cancelable extends Promise
{
constructor(executor = noop)
{
super((resolve, reject) => {
executor(v => {
/**
* @see https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Optional_chaining
*/
if (this?.canceled) {
this.silent || reject(new Error('Cancelled'))
return
}
resolve(v)
}, reject)
})
this.canceled = false
}
cancel(silent = false)
{
this.silent = silent
this.canceled = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment