Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Last active May 2, 2020 01:59
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 dead-claudia/0b236aadc97698c34b4ed7e75eb42e44 to your computer and use it in GitHub Desktop.
Save dead-claudia/0b236aadc97698c34b4ed7e75eb42e44 to your computer and use it in GitHub Desktop.
Promise synchronous settle
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