Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Last active December 3, 2019 02:46
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 duncanbeevers/830a1b40363ffd9502f85896388cbe66 to your computer and use it in GitHub Desktop.
Save duncanbeevers/830a1b40363ffd9502f85896388cbe66 to your computer and use it in GitHub Desktop.
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();
@duncanbeevers
Copy link
Author

duncanbeevers commented Dec 3, 2019

$ node proxyPromise.js
[promise1] x called with [ [length]: 0 ]
[promise2] x called with [ [length]: 0 ]
[promise1] y called with [ 'a', [length]: 1 ]
[promise2] y called with [ 'a', [length]: 1 ]
[promise1] z called with [ 'foo', 'bar', [length]: 2 ]
[promise2] z called with [ 'foo', 'bar', [length]: 2 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment