Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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