0

I've seen a similar question once, but I can't for the life of me figure out why this isn't working. I have a pretty simple program below that should wrap the exec function and return the result. However all it returns is undefined. Here's the function:

var exec = require('child_process').execSync;

quickexec = function(command) {
    exec(command, function(error, stdout, stderr) {
        if(error) {
            return error;
        } else {
            return stdout;
        }
    });
};

I call it like this console.log(quickexec('echo -n $USER')); and I get undefined everytime. However if I change the return in my function to a console.log it works. I thought that it was an async problem which is why I started using execSync, but it didn't change anything.

watzon
  • 2,401
  • 2
  • 33
  • 65
  • *"I thought that it was an async problem"* it is. Why do you think you have to pass a callback in the first place? Also, `quickexec` doesn't contain a `return` statement. What solution are you looking for? Technically it's a duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/218196) – Felix Kling Dec 13 '15 at 07:28

1 Answers1

0

quickexec() does not actually return anything. The return inside it are in the async callback which happens long after quickexec() has already returned. You can't synchronously return an asynchronous result. This is a common issue when learning how to do proper asynchronous programming in node.js.

If you need a synchronous result, you can use execsync(), but usually the best design is to use the asynchronous result in the callback.

var quickexec = function(command, callback) {
    exec(command, function(error, stdout, stderr) {
        if(error) {
            callback(error);
        } else {
            callback(null, stdout);
        }
    });
};

quickexec('echo -n $USER', function(err, result) {
    // use the result here in the callback
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979