javascript - 通过 promise 返回 ES6 代理时堆栈溢出

标签 javascript node.js proxy ecmascript-6 es6-promise

我正在尝试拦截 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/

相关文章:

javascript - 使用参数将用户重定向到另一个 PHP 页面

使用 Node Express 在 digital ocean 中设置 mysql

javascript - ES 模块命名导入是否可以实现 native Node 绝对(即根相对)路径?

windows - 如何在docker工具箱中设置代理?

javascript - 循环使用 Ajax 的函数。仅在 IE 中失败。其他所有浏览器都可以正常工作

javascript - 单击淡出 div 然后淡入

php - ReCaptcha 不接受任何字符串

javascript - 如何在强大(Node.js)中取消用户上传?

php - 在代理服务器后面时从 CakePHP 访问数据库

python - 如何通过 http 代理传递所有 Python 的流量?