【问题标题】:Halt the promise chain or stop the runInNewContext returning promise chain停止承诺链或停止 runInNewContext 返回承诺链
【发布时间】:2018-01-02 15:31:39
【问题描述】:

我在使用runInNewContext 执行代码时遇到了vm 的问题。

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

 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?还是在等待中超时?

【问题讨论】:

    标签: node.js promise nodevm


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      目前已通过babeltransformFromAst 使用代码注入解决。

      如果执行时间超过每个函数声明和函数表达式开头的指定时间跨度,则只需throw error

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-29
        • 2017-02-18
        • 2017-06-15
        • 1970-01-01
        • 2017-11-24
        • 2014-11-16
        • 2017-03-03
        • 2023-01-27
        相关资源
        最近更新 更多