Last active
May 6, 2019 08:05
-
-
Save xxjinwei/6a7bfd3dbce03a92af3146e8f262540d to your computer and use it in GitHub Desktop.
cancelable promise
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
/** | |
* @file cancelable promise | |
*/ | |
const pending = Promise.race.bind(Promise, []); | |
export default function cancellablePromise(fn) { | |
let isPending = true; | |
const patch = fn => (...args) => { | |
isPending = false; | |
if (fn) { | |
fn(...args); | |
} | |
}; | |
return new Promise((fulfill, reject) => { | |
const cancel = () => { | |
if (isPending) { | |
fulfill(pending()); | |
} | |
}; | |
fn(patch(fulfill), patch(reject), cancel); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment