Why back-end with nodeVM not sending result of async function?

67 views Asked by At

I trying to make online compiler JS

if i send code to back-end like hello world:

Front-end sending code and get response of compiling code

sending some thinks to compiling and got response

but if i try to send some fetch i get this:

example code with fetch

// Function that returns a Promise
function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation (e.g., fetching data from an API)
    setTimeout(() => {
      const success = true; // Simulate success or failure

      if (success) {
        const data = { message: 'Data fetched successfully' };
        resolve(data); // Resolve the Promise with the data
      } else {
        reject(new Error('Failed to fetch data')); // Reject the Promise with an error
      }
    }, 2000); // Simulating a 2-second delay
  });
}

// Using the Promise with then and catch
fetchData()
  .then((data) => {
    console.log('Success:', data.message);
  })
  .catch((error) => {
    console.error('Error:', error.message);
  });

problem, response if i send some async function, is empty but in cosole back-end i see this:

in back-end i see response what i expecting to get in front-end

My back-end code with ExpressJS:

const express = require('express');
const router = express.Router();
const { NodeVM } = require('vm2');

router.post('/execute', async (req, res) => {
  const code = req.body.code;

  let consoleOutput = '';

  const vm = new NodeVM({
    console: 'redirect',
    sandbox: {
      console: {
        log: (...args) => {
          console.log(...args);
          consoleOutput += args.join(' ') + '\n';
        }
      },
      setTimeout,
      setInterval,
      clearTimeout,
      clearInterval,
      JSON,
      Math,
      Date,
      RegExp,
      Array,
      Object,
      fetch,
      alert: message => {
        consoleOutput += 'ALERT: ' + message + '\n';
      }
    }
  });

  try {
    await vm.run(code);
  
      res.status(200).json({ consoleOutput });
    
  } catch (error) {
    res.status(500).json({ error: error.message });
    return;
  }
});

module.exports = router;

I expecting to get some response by compiling some async functions like this:

example code

or some ideas what to use to make simple pure js compiler, thanks in advance to everyone who will respond

0

There are 0 answers