Created
February 13, 2018 23:43
-
-
Save ccnokes/4cd01aa5849a5ade7f5dab01afef64e9 to your computer and use it in GitHub Desktop.
Promise wrapper with abort function
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
function makeAbortablePromise(promise, abort = () => {}) { | |
const promiseWithAbort = { | |
abort, | |
promise, | |
// proxy methods | |
then: (...args) => { | |
promiseWithAbort.promise = promiseWithAbort.promise.then.apply( | |
promiseWithAbort.promise, | |
args | |
); | |
return promiseWithAbort; | |
}, | |
catch: (...args) => { | |
promiseWithAbort.promise = promiseWithAbort.promise.catch.apply( | |
promiseWithAbort.promise, | |
args | |
); | |
return promiseWithAbort; | |
}, | |
finally: (...args) => { | |
promiseWithAbort.promise = promiseWithAbort.promise.finally.apply( | |
promiseWithAbort.promise, | |
args | |
); | |
return promiseWithAbort; | |
} | |
}; | |
return promiseWithAbort; | |
} | |
// test it out... | |
const { abort, promise } = makeAbortablePromise(Promise.resolve(123), () => console.log('aborted')) | |
.then(x => x + 1) | |
.then(x => x + 1, () => console.log("test")) | |
.then(console.log) // -> 125 | |
.catch(console.error); | |
abort(); // -> 'aborted' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment