Created
May 16, 2018 21:38
-
-
Save masterT/9b79453b8af0ced8ff551e49e76efe74 to your computer and use it in GitHub Desktop.
Cancelable Promise
This file contains hidden or 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
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