如何知道虚拟机脚本何时完成执行?

问题描述 投票:1回答:1

这里是示例代码:

const vm = require('vm');

// Pass setTimeout function to the sandbox
const sandbox = { setTimeout };

// Will assign 'stackoverflow' to global variable `test` after 2 seconds
const rawCode = 'setTimeout(() => { test = "stackoverflow"; }, 2000);';

const script = new vm.Script(rawCode);
script.runInNewContext(sandbox);

// Output: {
//  setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] }
// }
console.log(sandbox);

// Output: {
//  setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
//  test: 'stackoverflow'
// }
setTimeout(() => console.log(sandbox), 2000);

有没有办法告诉vm上下文中的代码已完全执行,并且其事件循环中没有回调?

node.js
1个回答
0
投票

根据Github上的this评论(由bnoordhuis撰写:]

上下文共享事件循环。

因此,如果我们在VM代码中调用setTimeout,则回调将与“父代”注册在同一队列中。此后,无法判断回调是属于VM代码还是属于父代码。因此,我们无法跟踪VM中已注册的回调的数量,也无法确定何时完成运行。

我创建了a feature request on Node.js project,但显然有许多挑战需要克服。

© www.soinside.com 2019 - 2024. All rights reserved.