Skip to content

Instantly share code, notes, and snippets.

@moodysalem
Last active April 9, 2024 18:06
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moodysalem/dddfc2806225ab455c026bfbdd363c03 to your computer and use it in GitHub Desktop.
Save moodysalem/dddfc2806225ab455c026bfbdd363c03 to your computer and use it in GitHub Desktop.
ES6 Cancellable Promise Wrapper
/**
* Returns a promise that has a cancelled method that will cause the callbacks not to fire when it resolves or rejects
* @param promise to wrap
* @returns new promise that will only resolve or reject if cancel is not called
*/
export default function cancellable(promise) {
var cancelled = false;
const toReturn = new Promise((resolve, reject) => {
promise.then(() => {
if (!cancelled) {
resolve.apply(this, arguments);
}
}, () => {
if (!cancelled) {
reject.apply(this, arguments);
}
})
});
toReturn.cancel = () => cancelled = true;
return toReturn;
};
@moodysalem
Copy link
Author

This simple function takes a promise and returns a new promise that will not resolve or reject if cancelled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment