我正在尝试实现一种在Node.js VM中运行“顺序编写”异步JS代码的方法,并获得对相应上下文对象的访问权限。我尝试使用由await
转换的即将发布的ES7 babel.js
功能。
在我看来,script.runInContext()在后台运行,而主循环继续,因此我无法从VM的上下文中获得结果。
我的示例代码如下:
var vm = require('vm');
var request = require('request-promise');
var babel = require("babel-core");
// VM context object
var contextCache = {
context: {
request: request
}
};
// ES 7 code
var code = "var res = await request('http://www.google.de')";
// Wrap the code
code = "(async function() { " + code + " })()";
// Transpile code ES7 -> ES5
var regeneratedCode = babel.transform(code, { "ast": false, "presets": ["stage-0"] }).code
// Create VM context
var vmContext = new vm.createContext(contextCache.context);
// Create virtual script
var script = new vm.Script(regeneratedCode);
// Run script
script.runInContext(vmContext, {displayErrors: true, timeout: 30000});
// Check if variable was set -> Is undefined
console.log(contextCache.context.res);
有没有办法以同步方式从上下文评估中检索异步结果?
参考文献:
答案 0 :(得分:4)
I found a way to get this working... Basically it's using the Apples::Apples() : Fruits("Apple", BREAKFAST), number( 5 )
{
}
variable for the context object inside the executed code, and calling a callback function from inside as the last operation:
this
答案 1 :(得分:0)
const vm = require('vm');
(async () => {
const sandbox = {
a: 1
};
await new Promise(resolve => {
sandbox.resolve = resolve;
const code = 'Promise.resolve(2).then(result => {a = result; resolve();})';
const script = new vm.Script(code);
const context = new vm.createContext(sandbox);
script.runInContext(context);
});
console.log(sandbox.a); // 2
})();
答案 2 :(得分:0)
您可以删除var
,而不用将this.
替换为var
。
这将使变量对于上下文是全局的,然后可以在vm外部进行访问。