我们如何从 node.js 中的回调函数访问变量? [英] How can we access variable from callback function in node.js?

查看:28
本文介绍了我们如何从 node.js 中的回调函数访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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('
','');
      }
);

var username = ?

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

How can I find username outside from exec function ?

推荐答案

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

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('
','');
        callback( username );
    });


由于 JavaScript 的异步特性,您不能这样做:


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('
','');
    });

    child();

    console.log( username );

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

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


回调说明:

    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.

这篇关于我们如何从 node.js 中的回调函数访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆