Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
How to wait for node exec response?

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!!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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)
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
      }
    });
  });
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda