0

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.

Vista Chyi
  • 75
  • 7
  • 2
    Duplicate of [Node exits without error and doesn't await promise (Event callback)](https://stackoverflow.com/questions/46914025/node-exits-without-error-and-doesnt-await-promise-event-callback) – Guy Incognito Dec 09 '20 at 15:12
  • I think this is a different problem. If I remove **microtaskMode** options, it will have a different behavior. I think there is something wrong caused by this options. – Vista Chyi Dec 09 '20 at 16:26

0 Answers0