我在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
?或在等待中超时?