Skip to content

Instantly share code, notes, and snippets.

@xxjinwei
Last active May 6, 2019 08:05
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 xxjinwei/6a7bfd3dbce03a92af3146e8f262540d to your computer and use it in GitHub Desktop.
Save xxjinwei/6a7bfd3dbce03a92af3146e8f262540d to your computer and use it in GitHub Desktop.
cancelable promise
/**
* @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