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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19442829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:01:35  来源:igfitidea点击:

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

javascriptnode.jscallback

提问by Devang Bhagdev

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 ?

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

回答by Matthias Holdorf

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

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

    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:


由于 JavaScript 的异步特性,你不能做这样的事情:

    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.

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


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.

回答by Sahil Chitkara

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

您可以在具有回调的函数中编写“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);
});