2017-06-16 125 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