Consider the following node code that invokes an async function with node vm:
const vm = require('vm');
const ctx = new vm.createContext({
console: console,
foo: function(){
return new Promise(r => {console.log(2); r()})
}
})
console.log("START");
const script = "async function main(){ console.log(1); await foo(); console.log(3); }";
new vm.Script(script).runInContext(ctx);
new vm.Script("main()").runInContext(ctx);
console.log("END");
The output of the code is: 1, 2, END, 3
How can I make sure that the async main()
function has naturally terminated before allowing "END" to happen, so that the output would be: 1, 2, 3, END?