Last active
April 9, 2024 18:06
-
-
Save moodysalem/dddfc2806225ab455c026bfbdd363c03 to your computer and use it in GitHub Desktop.
ES6 Cancellable Promise Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This simple function takes a promise and returns a new promise that will not resolve or reject if cancelled.