我正在尝试拦截 ES6 代理上的方法调用,以便能够在我从代理获得的信息之间做一些事情。现在,在我的例子中,在从某种工厂创建和返回代理之前需要做一些事情。由于所有这些东西,我决定将先决条件包装到一个 promise 函数中,这样我就可以将代理创建链接到它上面,并通过 promise 链返回生成的代理。下面是重现问题的代码:
proxy_factory.min.js
'use strict';
// require('harmony-reflect');
class ProxyFactory {
create(options) {
const self = this;
const handler = {
get(target, propertyKey, receiver) {
if (propertyKey === 'then') {
return function proxyPromiseWrapper(thenCallback) {
const innerProxy = self.create(options);
return thenCallback(innerProxy);
};
}
return function resourceFunctionProxy() {
const callContext = {
target: target,
method: propertyKey,
args: arguments,
thisContext: this
};
const resourceInstanceMethod = Reflect.get(options.originalObject, callContext.method);
return resourceInstanceMethod.apply(callContext.thisContext, callContext.arguments);
};
}
};
return new Proxy(options.originalObject, handler);
}
}
module.exports = ProxyFactory;
测试.js
'use strict';
const Promise = require('bluebird');
const ProxyFactory = require('./proxy_factory.min.js');
const proxyFactory = new ProxyFactory();
function createProxyWithPromise() {
const TestClass = class {
doSomething() {
return Promise.resolve('promise return value');
}
};
const options = {
originalObject: new TestClass()
};
return Promise.resolve()
.then(() => {
return proxyFactory.create(options);
});
}
function test() {
createProxyWithPromise()
.then((proxy) => {
const result = proxy.doSomething();
console.log(result); // should output 'promisereturnvalue'
});
}
test();
在代理上调用 doSomething() 之前,then() 函数被一遍又一遍地调用,导致堆栈溢出。 我已经在 node.js github 问题中问过这个问题,你可以在这里找到之前的对话:https://github.com/nodejs/node/issues/8082 也许它可以帮助帮助我的人 ;)
最佳答案
你的问题是你的代理总是返回一个函数来访问任何属性,包括then
。这将使 promises 实现将它视为一个 thenable,试图解决它——你的代码在那里出现了可怕的错误。但是您应该解决问题的根源:
get (target, propertyKey, receiver) {
if (!(propertyKey in target))
return undefined;
else if (typeof target[propertyKey] != "function")
return …;
else
return function resourceFunctionProxy() {
…
关于javascript - 通过 promise 返回 ES6 代理时堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951001/