Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda