简体   繁体   English

Node.js execSync返回未定义但console.log有效

[英]Node.js execSync returning undefined but console.log works

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. 我下面有一个非常简单的程序,应该包装exec函数并返回结果。 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')); 我这样称呼它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. 但是,如果我将函数的返回值更改为console.log,则它可以工作。 I thought that it was an async problem which is why I started using execSync , but it didn't change anything. 我认为这是一个异步问题,这就是为什么我开始使用execSync ,但是它没有任何改变。

quickexec() does not actually return anything. quickexec()实际上不返回任何内容。 The return inside it are in the async callback which happens long after quickexec() has already returned. 它内部的return位于异步回调中,该回调在quickexec()已经返回很长时间之后发生。 You can't synchronously return an asynchronous result. 您无法同步返回异步结果。 This is a common issue when learning how to do proper asynchronous programming in node.js. 在学习如何在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. 如果需要同步结果,则可以使用execsync() ,但是通常最好的设计是在回调中使用异步结果。

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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM