How to proxy a promise in javascript es6

I am trying to proxy a promise in my 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)});
Run code

This does not work, I get "TypeError:" and then "raises an object that does not implement the Promise interface".

+6
source share
2 answers

You need your handler to implement the get () hook and return the associated versionprom.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)});

Please note that if you just want to proxy all means of access, the function getwill look like this:

var promProxy = new Proxy(prom, {
  get: function(target, prop) {
    var value = target[prop];
    return typeof value == 'function' ? value.bind(target) : value;
  }
});

bind ensures that the function will not be called incorrectly when dealing with Native objects such as Promises or the console.

: / Proxies, Harmony-Reflect, .

+5

, . , - , , . , , , .

-, :

var p = new Promise(function(resolve, reject) {
  var proxy = get_my_proxy();
  resolve(proxy);
});

, darn resolve then ( - ). , , , , (, , , , ) - null then - , resolve() , Promise ( Thenable).

get: function(target, prop) {
  if (prop === 'then') return null; // I'm not a Thenable
  // ...the rest of my logic
}
0

All Articles