I want run some async code using vm
module, after reading the doc, I notice that version 14 add a options named 'microtaskMode' which prevent async function escaping timeout.
But when I add this option to my code, something strange happened, here is my code:
const vm = require('vm');
const result = vm.runInNewContext(`
(async function(require) {
const axios = require('axios');
const res = await axios.get('https://www.apple.com/');
return res.body;
})(require)
`, {
require
}, {
timeout: 5000,
microtaskMode: 'afterEvaluate'
});
console.log(result);
result.then(
() => console.log('succeeded'),
() => console.log('failed')
);
and the output:
Promise { <pending> }
Process finished with exit code 0
The promise is always pending, none of callback will be invoked, and process exit with code 0. My Node.js version is 15.2.1. Why?
And another question, is there any way to run async function in vm context instead of awaiting it in current context? I want to get the final returned value instead of a pending promise :(
Behavior will be different if remove the microtaskMode options.