Last active
September 30, 2019 18:34
-
-
Save davidbarral/d4113a6d04acf476a5a2d8976d65cc2c to your computer and use it in GitHub Desktop.
Lazy promises
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
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