title: In Node.js, how can I return a Promise from vm2?
body: <p>I have some asynchronous JavaScript code, which I'd like to run using vm2 / NodeVM.</p>
  
  <p>The code tests two functions: a user-submitted function <code>evenAndOdd</code> and a pre-defined function <code>solution</code> using Node's built-in <code>assert</code> library.</p>
  
  <p>My question is, how can I get the my resolved Promise out of <code>vm.run()</code>?</p>
  
  <p><strong>The Aynchronous Code</strong></p>
  
  <p>This is the test code I want to turn into a string and run using <code>vm2</code>: </p>
  
  <pre><code>const assert = require('assert');
  
  function evenAndOdd(arr) {
    return [arr.filter(el =&gt; el % 2 === 0).sort(), arr.filter(el =&gt; el % 2 === 1).sort()];
  };
  
  function solution(arr) {
    return [arr.filter(el =&gt; el % 2 === 0).sort(), arr.filter(el =&gt; el % 2 === 1).sort()];
  };
  
  const runTest = async () =&gt; {
  
    return new Promise((resolve, reject) =&gt; {
  
      const map = new Map();
      const tests = 10;
  
      for (let i = 0; i &lt; tests; i++) {
  
        let randLength = parseInt(Math.random() * 19 + 1);
        let randArray = [...Array(randLength)].map(e =&gt; ~~(Math.random() * randLength));
  
        const test = async () =&gt; {
          return assert.deepEqual(evenAndOdd(randArray), solution(randArray));
        }
  
        const description = "TEST CASE: evenAndOdd([" + randArray + "}]) EXPECT: [[" + solution(randArray)[0] + "], [" + solution(randArray)[1] + "]] GOT: [[" + evenAndOdd(randArray)[0] + "], [" + evenAndOdd(randArray)[1] + "]]";
  
        test()
          .then(() =&gt; {
            map.set(description, true);
            if (map.size === tests) {
              resolve(map);
            };
          })
          .catch(() =&gt; {
            map.set(description, false);
            if (map.size === tests) {
              resolve(map);
            };
          })
      }
    })
  }
  </code></pre>
  
  <p>If I append the following code, I get exactly what I want logged to the console:</p>
  
  <pre><code>runTest().then((result) =&gt; {
    console.log(result)
  });
  </code></pre>
  
  <p><strong>The <code>vm</code> Code</strong></p>
  
  <p>My question is, how do I get the resolved promise from <code>vm.run()</code>?</p>
  
  <pre><code>const { NodeVM } = require('vm2');
  
    const vm = new NodeVM({
      console: 'inherit',
      sandbox: {},
      require: {
        external: true,
        builtin: ['assert'],
        import: ['assert'],
        root: "./",
      },
    });
  
  const result = vm.run(stringifiedJavaScript, 'vm.js');
  </code></pre>
  
  <p>Right now, the <code>result</code> variable above is undefined. </p>