How can we access variable from callback function

2019-01-21 17:06发布

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 = ?

How can I find username outside from exec function ?

2条回答
爷的心禁止访问
2楼-- · 2019-01-21 17:26

You can write the "exec" statement in a function that has a callback... Like This

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);
});
查看更多
爷的心禁止访问
3楼-- · 2019-01-21 17:41

You can pass the exec function a callback. When the exec function determines the username, you invoke the callback with the username.

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


Due to the asynchronous nature of JavaScript, you can't do something like this:

    var username;

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

    child();

    console.log( username );

This is because the line console.log( username ); won't wait until the function above finished.


Explanation of callbacks:

    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.
查看更多
登录 后发表回答