Last active
May 2, 2020 01:59
-
-
Save dead-claudia/0b236aadc97698c34b4ed7e75eb42e44 to your computer and use it in GitHub Desktop.
Promise synchronous settle
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
const call = Function.call.bind(Function.call) | |
// `onSettled` is just `onSettled(value, isSuccess)`. | |
Promise.hookIntoSettlement = (thenable, onSettled) => { | |
function settle(value) { | |
let settled = false | |
let then | |
function fail(e) { | |
if (!settled) { | |
settled = true | |
onSettled(e, false) | |
} | |
} | |
function pass(v) { | |
if (!settled) { | |
settled = true | |
settle(v) | |
} | |
} | |
if (value != null) { | |
try { | |
then = value.then | |
if (then != null) { | |
call(then, value, pass, fail) | |
return | |
} | |
} catch (e) { | |
fail(e) | |
return | |
} | |
} | |
onSettled(value, true) | |
} | |
settle(thenable) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment