0

我在vm使用runInNewContext.

自定义代码可以返回一个可能是嵌套的并且可以具有嵌套调用堆栈的承诺。代码如下所示

 function executeInSandbox(code, sandbox){
  return Async((code, _sandbox) => {
    let fn = `"use strict";
              this.result = async(() => {
                  ${code}
              })();`;
    var script = new vm.Script(fn);
    return Await(
      script.runInNewContext(_sandbox, {
        displayErrors: true,
        timeout: 30000
      })
    );
  })(code, sandbox);
};
result = Await(executeInSandbox(code, sandbox))

现在的问题是,如果承诺的处理时间超过 20 秒,我想停止处理。

如果代码是递归的并且带有嵌套的 Promise,它会在 20 秒内被堆叠,但现在尝试执行调用堆栈,这需要超过几分钟并且不可停止,最后会出现堆栈溢出问题。

我尝试添加以下Promise.race

let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
  clearTimeout(id);
  reject('Timed out in '+ 2000 + 'ms.')
}, 2000);
});
let fn = `"use strict";
        this.result = async(() => {
            ${code}
        })();`;
var script = new vm.Script(fn);
let codePromise = script.runInNewContext(_sandbox, {
displayErrors: true,
timeout: 30000
});
return Await(
Promise.race([
  codePromise,
  timeout
])
);
})(code, sandbox);

它有点像将控制权排除在功能之外,但是承诺链会继续执行。

有没有办法停止codePromise?或在等待中超时?

4

2 回答 2

1

您需要将 20 秒超时视为代码的主要功能。所有的承诺必须要么解决要么拒绝。如果一个函数需要超时,它必须通过解决或拒绝来完成。不要假设您可以从外部强制执行此操作。

于 2018-01-02T17:13:04.030 回答
0

babel目前通过's使用代码注入解决transformFromAst

只要throw error执行时间超过每个函数声明和函数表达式开始时的指定时间跨度。

于 2018-01-03T14:36:13.660 回答