Skip to content

Instantly share code, notes, and snippets.

@davidbarral
Last active September 30, 2019 18:34
Show Gist options
  • Save davidbarral/d4113a6d04acf476a5a2d8976d65cc2c to your computer and use it in GitHub Desktop.
Save davidbarral/d4113a6d04acf476a5a2d8976d65cc2c to your computer and use it in GitHub Desktop.
Lazy promises
Promise.cancelable = pendingPromise => {
let lazyCb = null;
let settled = false;
let canceled = false;
const promise = Promise.resolve(pendingPromise).then(() => {
settled = true;
if (canceled) {
return;
}
return lazyCb && pendingPromise.then(lazyCb);
});
return {
then: cb => {
if (canceled) {
return;
}
if (settled) {
promise.then(cb);
return;
}
lazyCb = cb;
},
cancel: () => {
if (!settled) {
canceled = true;
}
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment