Skip to content

Instantly share code, notes, and snippets.

@Anenth
Created September 21, 2017 14:52
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 Anenth/f270bc584565769624bb9630b549680b to your computer and use it in GitHub Desktop.
Save Anenth/f270bc584565769624bb9630b549680b to your computer and use it in GitHub Desktop.
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