0

I have function below.

function sh(cmd) {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err);
        std_value.flush();
        std_value.set("error");
      } else {
        console.log({stdout, stderr});
        std_value.flush();
        std_value.set(stdout);
        console.log('std_value in ' + std_value.result);
      }
    });
    console.log('std_value out ' + std_value.result);
    return std_value.result;
}

I want to sh(cmd) return output of cmd. So i am using the following(it is little bit shitty). But exec is async function, so outer std_value.result will be the value from last call. Is it normal way to create sh(cmd), which wiil return stdout or I should use promises?

1

2 Answers 2

1

You can make use of promise here since you can not return value from the callback/async function.

function sh(cmd) {
  return new Promise((resolve, reject) => {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err);
        std_value.flush();
        std_value.set("error");
        reject(err);
      } else {
        console.log({stdout, stderr});
        std_value.flush();
        std_value.set(stdout);
        console.log('std_value in ' + std_value.result);

        resolve(std_value.result);
      }
    });
  })
}

sh().then(val => {
  console.log(val); //this should console the value of std_value.result
})

Note: I don't know where did you get std_value.

Sign up to request clarification or add additional context in comments.

Comments

1

function sh(cmd, callback) {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err);
        std_value.flush();
        std_value.set("error");
        if(!!callback) {
          callback(err);
        }
      } else {
        console.log({stdout, stderr});
        std_value.flush();
        std_value.set(stdout);        
        console.log('std_value in ' + std_value.result);
        if(!!callback) {
          callback(std_value.result);
        }
      }
    });
}

sh("run", function(result) {
  console.log(result);
});

You can implement the same with callback like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.