Skip to content

Instantly share code, notes, and snippets.

@dino-su
Last active November 19, 2019 07:34
Show Gist options
  • Save dino-su/e580a0d87607ed972d772324c37dbb7d to your computer and use it in GitHub Desktop.
Save dino-su/e580a0d87607ed972d772324c37dbb7d to your computer and use it in GitHub Desktop.
Fluent Promise Proxy
// Credit: https://gist.github.com/malko/d3dee36e7d0d927654439f4c01c8ca0c
function fluentProxy (target, promise = Promise.resolve()) {
return new Proxy(target, {
get(target, property) {
if (target[property] instanceof Function) {
return (...args) => fluentProxy(target, promise.then(() => target[property](...args)));
}
}
});
};
class Person {
say(text, delay = 300) {
return new Promise(resolve => {
setTimeout(() => {
resolve(console.log(text));
}, delay);
});
}
}
const me = fluentProxy(new Person());
me.say('hello').say('world').say('bye', 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment