Last active
December 3, 2019 02:46
-
-
Save duncanbeevers/830a1b40363ffd9502f85896388cbe66 to your computer and use it in GitHub Desktop.
jacobRothstein proxy promise thing https://twitter.com/jacobrothstein/status/1201641829269000192
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
function proxyPromise(promise) { | |
const acc = []; | |
function createFnProxy(prop) { | |
return function(...args) { | |
acc.push([prop, args]); | |
return proxy; | |
}; | |
} | |
const proxy = new Proxy(promise, { | |
get(obj, prop) { | |
return createFnProxy(prop); | |
}, | |
}); | |
function cycle(_promise) { | |
return _promise.then((resolution) => { | |
if (!acc.length) { | |
return _promise; | |
} | |
const [prop, args] = acc.shift(); | |
const resolutionResult = resolution[prop](...args); | |
return cycle( | |
resolutionResult && resolutionResult.then | |
? resolutionResult | |
: Promise.resolve(resolutionResult) | |
); | |
}); | |
} | |
cycle(promise); | |
return proxy; | |
} | |
function main() { | |
const promise1 = Promise.resolve({ | |
x(...args) { | |
console.log('[promise1] x called with %o', args); | |
return { | |
y(...args2) { | |
console.log('[promise1] y called with %o', args2); | |
return { | |
z(...args3) { | |
console.log('[promise1] z called with %o', args3); | |
return null; | |
}, | |
}; | |
}, | |
}; | |
}, | |
}); | |
const promise2 = new Promise((resolve, reject) => { | |
const obj = { | |
x(...args) { | |
console.log('[promise2] x called with %o', args); | |
return obj; | |
}, | |
y(...args) { | |
console.log('[promise2] y called with %o', args); | |
return obj; | |
}, | |
z(...args) { | |
console.log('[promise2] z called with %o', args); | |
return obj; | |
}, | |
}; | |
resolve(obj); | |
}); | |
const proxy1 = proxyPromise(promise1); | |
proxy1 | |
.x() | |
.y('a') | |
.z('foo', 'bar'); | |
const proxy2 = proxyPromise(promise2); | |
proxy2 | |
.x() | |
.y('a') | |
.z('foo', 'bar'); | |
} | |
main(); |
Author
duncanbeevers
commented
Dec 3, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment