我们如何从node.js中的回调函数中访问变量?

时间:2013-10-18 06:16:09

标签: javascript node.js callback

var sys = require('sys');
var exec = require('child_process').exec;
var cmd = 'whoami';
var child = exec( cmd,
      function (error, stdout, stderr) 
      {
        var username=stdout.replace('\r\n','');
      }
);

var username = ?

如何在exec函数外找到用户名?

2 个答案:

答案 0 :(得分:29)

您可以将exec函数传递给回调函数。当exec函数确定用户名时,您使用用户名调用回调。

    var child = exec(cmd, function(error, stdout, stderr, callback) {
        var username = stdout.replace('\r\n','');
        callback( username );
    });


由于JavaScript的异步特性,您无法执行以下操作:

    var username;

    var child = exec(cmd, function(error, stdout, stderr, callback) {
        username = stdout.replace('\r\n','');
    });

    child();

    console.log( username );

这是因为行console.log( username );不会等到上面的函数完成。


回调说明:

    var getUserName = function( callback ) {            
        // get the username somehow
        var username = "Foo";    
        callback( username );
    };

    var saveUserInDatabase = function( username ) {
        console.log("User: " + username + " is saved successfully.")
    };

    getUserName( saveUserInDatabase ); // User: Foo is saved successfully.

答案 1 :(得分:4)

您可以在具有回调功能的函数中编写“exec”语句... 喜欢这个

var sys = require('sys');
var exec = require('child_process').exec;
var cmd = 'whoami';
function execChild(callback){
    var child = exec( cmd,
          function (error, stdout, stderr) 
          {
            username=stdout.replace('\r\n','');
             callback(username);
          }
 )};
    execChild(function(username){
    console.log(username);
});