Skip to content

Instantly share code, notes, and snippets.

@theseyi
Created October 26, 2016 20:31
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 theseyi/748dbaf8bc3aab614dd2b47633fba55b to your computer and use it in GitHub Desktop.
Save theseyi/748dbaf8bc3aab614dd2b47633fba55b to your computer and use it in GitHub Desktop.
Cancelable Promise
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment