Monday, April 8, 2019

javascript - How can we access variable from callback function in node.js?

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.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...