Skip to content

Instantly share code, notes, and snippets.

@masterT
Created May 16, 2018 21:38
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 masterT/9b79453b8af0ced8ff551e49e76efe74 to your computer and use it in GitHub Desktop.
Save masterT/9b79453b8af0ced8ff551e49e76efe74 to your computer and use it in GitHub Desktop.
Cancelable Promise
export class CanceledError extends Error {
constructor (promise) {
super()
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CanceledError)
}
this.promise = promise
this.isCanceled = true
}
}
/**
* Make a Promise cancelable.
*
* Example:
*
* let cancelablePromise = new CancelablePromise(
* api.get('/foo')
* )
* cancelablePromise
* .promise
* .then((results) => console.log(results))
* .catch((error) => {
* if (!error.isCanceled) {
* console.log('Something went wrong.')
* } else {
* console.log('Promise canceled!')
* }
* })
*
* cancelablePromise.cancel()
* // "Promise canceled!"
*
*/
export class CancelablePromise {
constructor (promise) {
this.isCanceled = false
// Wrap original Promise in a new Promise.
this.promise = new Promise((resolve, reject) => {
promise.then(
(value) => {
if (this.isCanceled) {
reject(new CanceledError(promise))
} else {
resolve(value)
}
},
(error) => {
if (this.isCanceled) {
reject(new CanceledError(promise))
} else {
reject(error)
}
}
)
})
}
cancel () {
this.isCanceled = true
}
}
export default CancelablePromise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment