Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!