Last active
December 11, 2018 10:02
-
-
Save tbranyen/07d5ae9b4eefd060a70dccd3a52287ad to your computer and use it in GitHub Desktop.
Make Cancellable Promise
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
Promise.makeCancellable = promise => { | |
const deferred = {}; | |
const promise = new Promise((resolve, reject) => { | |
deferred.reject = reject; | |
// Invoke the fetch argument with the matching args... only resolve if not | |
// aborted. | |
promise | |
.then(resp => !deferred.aborted && resolve(resp)) | |
.catch(ex => !deferred.aborted && reject(ex)); | |
}); | |
promise.abort = function() { | |
deferred.reject(null); | |
deferred.aborted = true; | |
return promise; | |
}; | |
return promise; | |
}; | |
// Usage... | |
Promise.makeCancellable(fetch('/someurl')).then(handleResponse).catch(ex => { | |
// Only handle real errors... | |
if (ex !== null) { | |
throw ex; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment