您可以向 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.