Home > Mobile >  How to wait for node exec response?
How to wait for node exec response?

Time:02-20

how can I use a callback tor a promise correctly to get the result from a node exec in the condole.log() function?

import { exec } from 'child_process';
const check = () => {
    exec(`...`, (err, stdout) => {
        if (err) {
         return false         
        }
        else {
         return true
        }
    })
}
console.log(check()) // getting undefined

I've tried using .on('exit') but none worked... would love to get some help here. THANKS!!

CodePudding user response:

You need to wrap the call in a promise to get the return of the callback:

import { exec } from 'child_process'

const check = () => {
  return new Promise((resolve) => {
    exec(`...`, (err, stdout) => {
        if (err) {
         resolve(false)       
        }
        else {
         resolve(true)
        }
    })
  })
}

By not rejecting on an error in the callback you can instead resolve the promise and return false instead. If you used the reject parameter on the promise call you would need to handle that error by chaining a .catch() call. To keep the implementation similar to what you already have I have omitted it and instead resolved the promise with false.

Then you can use .then() on the call to check and get the desired results:

check().then(res => {
  console.log(res)
})

CodePudding user response:

You can either use the Promise constructor to do it yourself or you can use the util module to convert a callback invoking function into one that returns a promise

Using the util module

const util = require("util");
const exec = util.promisify(require("child_process").exec);

const check = async () => {
  const output = await exec(`echo hi`);

  console.log(output);
};

check();

Wrapping with the Promise constructor

import { exec } from "child_process";
const check = async () => {
  return new Promise((resolve, reject) => {
    exec(`echo hi`, (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        resolve(stdout);
      }
    });
  });
};
  • Related