How to Proxy a Promise in JavaScript es6 -
i'm trying proxy promise in native firefox (and using babel).
var prom = new promise(function(resolve, reject){resolve(42)}); var promproxy = new proxy(prom, {}); promproxy.then(function(response){console.log(response)});
this doesn't work, 'typeerror: 'then' called on object not implement interface promise.'
you need have handler implement get() trap , return bound version of prom.then
var prom = new promise(function(resolve, reject){resolve(42)}); var promproxy = new proxy(prom, { get: function(target, prop) { if (prop === 'then') { return target.then.bind(target); } } }); promproxy.then(function(response){console.log(response)});
note if want proxy all accessors, get
function this:
var promproxy = new proxy(prom, { get: function(target, prop) { var value = target[prop]; return typeof value == 'function' ? value.bind(target) : value; } });
bind
ensure function won't incorrectly called when you're dealing native objects such promises, or console.
edit: in instances browsers / node have outdated version of proxies, in case you'll want use harmony-reflect bring date.
Comments
Post a Comment