2017-06-16 130 views
0

我试图创建一个函数,它将在node.js中按名称搜索进程。这里是我的功能:JavaScript中的嵌套变量作用域

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); 
} 

这里的问题是,即使控制台输出运行,返回不会设置为true。我已经在我的代码顶部修改了声明为返回的公共变量,但这并不能解决问题。有谁知道我的问题是为什么?

回答

0

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); 
}); 
+0

嗯,这是做的伎俩,谢谢你亲切的先生。 – Ubspy