1

I am trying to run an async CMD command on with my Node server. Unfortunately my functions always throws an UnhandledPromiseRejectionWarning. I searched for results but never found a solution that fits my code.

(node:20704) UnhandledPromiseRejectionWarning: 0
(node:20704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I know that the error states I should use a catch block but I really dont know how I should implement that with the lambda implementation I used.

const exec = require('child_process');
    

const execWindowsCommand = new Promise(async (resolve, reject) => {
  const process = exec.spawn('cmd', [ '/c', 'dir' ]);
  process.on('data', data => resolve(data));
  process.on('error', err => reject(err));
  process.on('close', err => reject(err));
  process.on('unhandledRejection', function(reason, promise) {console.log(promise);});
});

    
    
app.get("/cmdWIN", async(req, res) => {
  execWindowsCommand()
  .then(function(value) {
    console.log(value);
    res.send(value);
  })
  .catch((error) => {
    console.error(error);
    res.send(error);
  });
});
Leschge
  • 146
  • 3
  • 11

0 Answers0