Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created February 13, 2018 23:43
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 ccnokes/4cd01aa5849a5ade7f5dab01afef64e9 to your computer and use it in GitHub Desktop.
Save ccnokes/4cd01aa5849a5ade7f5dab01afef64e9 to your computer and use it in GitHub Desktop.
Promise wrapper with abort function
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