Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cancellable promise
export const CancellablePromise = (promise) => {
let isCancelled = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
(...args) => (isCancelled ? reject('cancelled') : resolve(...args)),
error => (isCancelled ? reject('cancelled') : reject(error)),
);
});
return {
promise: wrappedPromise,
cancel() {
isCancelled = true;
},
};
};
const fetch_dogs_promise = CancellablePromise( fetchTheDogs() );
fetch_dogs_promise.cancel();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment