javascript中的嵌套变量作用域
我试图创建一个函数,在node.js中按名称搜索进程。以下是我的功能:javascript中的嵌套变量作用域,javascript,node.js,Javascript,Node.js,我试图创建一个函数,在node.js中按名称搜索进程。以下是我的功能: function findProcess(name) { //Global var so the scope of the function can reach the var var toReturn; ps.lookup( { command: name }, function(err, resultList) { if(err)
function findProcess(name)
{
//Global var so the scope of the function can reach the var
var toReturn;
ps.lookup(
{
command: name
}, function(err, resultList)
{
if(err)
{
throw new Error(err);
}
if(resultList.length > 0)
{
toReturn = true;
console.log("running");
}
else
{
toReturn = false;
}
});
console.log(toReturn);
}
这里的问题是,即使控制台输出正在运行,toReturn也不会设置为true。我在代码顶部声明toReturn是一个公共变量,但这并没有起作用。有人知道我的问题是什么吗?在
findProcess()
中添加第二个参数,这是一个回调函数,您将从ps.lookup()
回调函数中调用它。将所需的任何数据传递到此回调,在本例中为布尔值。例如:
function findProcess( name, callback ) {
ps.lookup({
command: name
}, function( err, resultList ) {
if( err ) throw new Error( err );
callback( resultList.length > 0 );
});
}
findProcess( 'something', function( isRunning ) {
console.log( 'is running?', isRunning );
});
啊,这就成功了,谢谢你,好心的先生。