2013-10-28 19 views
0
app.get("/server", function (req, res){ 
    connection.query("SELECT * from serverdb", function(err, rows) 
    { 
    var data = rows; 
    var reachabilityResultString=""; 
    var serverCount = rows.length; 
    var arrayWithReachabilityResultStrings = new Array(); 
    var insertReachabilityResultStringIntoArray; 
     for (var counterForServername = 0 ; counterForServername < serverCount; counterForServername++) 
     { 

      ls = childProcess.exec('ping ' + rows[counterForServername].ipadresse,function (error, stdout, stderr) 
      { 
       if (error) 
       { 
        console.log(error.stack); 
        console.log('Error code: '+error.code); 
        console.log('Signal received: '+error.signal); 
        var errorSignal = ("Signal received: " + error.signal); 
        var errorReachability = "Error"; 

       } 
       else 
       { 
        console.log('Child Process STDOUT: '+stdout); 
        console.log('Child Process STDERR: '+stderr); 
        pingOutput = String(stdout); 

        console.log(reachabilityResult(pingOutput)); 

        insertReachabilityResultStringIntoArray = arrayWithReachabilityResultStrings.push(reachabilityResult(pingOutput)); 
        console.log(arrayWithReachabilityResultStrings); 
       }; 

      ls.on('exit', function (code) { 
      console.log('Child process exited with exit code '+code); 

      }); 

      }); 
     }; 
    }); 
res.render("all.jade,{servers: data, status: arrayWithReachabilityResultStrings}); 
}); 

..well ..這是我的代碼。我的問題是,該程序首先用jadecode調用網站;我希望你明白我的意思。我想將arrayWithReachabilityResultStrings交付給all.jade,所以程序必須等到for循環結束。但我不知道如何讓它等待。我所知道的「問題」是的Node.js的異步行爲,但我不知道我怎麼能解決這個..Node.js.我應該使用什麼?下一個()?

+0

順便說一句,我必須使用MySQL .. – Selina

回答

1

剛修好你的失蹤「,撥動您的

res.render("all.jade,{servers: data, status: arrayWithReachabilityResultStrings});

一行它需要通過connection.query中的回調來調用,因爲它現在被調用的速度要快得多 如果你閱讀了一些關於javascript變量範圍的內容,那也是不錯的,This SO question在這方面做得很好

PS:很高興看到新人學習節點。

+0

我修好了,但程序不會等到循環完成。 – Selina

+0

是的,如果你想執行所有的ping命令執行後渲染,你要確保它們全部被執行。有幾種方法可以做到這一點 - 我會使用一個簡單的計數器。從0開始,每完成一次ping就增加1,並檢查計數器是否等於「serverCount」,那麼你知道所有先前的ping都已完成。對這個「計數」來說Doownside是因爲如果你忘記調用它,它永遠不會完成。 – Capaj

+1

Woooooow它運行..謝謝! – Selina

1

如果您需要運行任意數量的子命令並等待全部完成,則應考慮使用async.js等助手庫並使用async.queue流量控制功能。這種協調在節點到手工代碼中實際上有點棘手,沒有任何流量控制功能。但是,這當然是可能的。在這種情況下,您需要一個單獨的done計數器,您可以在每個「退出」事件中增加計數器,並且當您的所有子進程都已啓動並且所有子進程都已完成時,就完成了。

+0

async.js現在已安裝,應使用哪個Control Flow模塊? timesSeries? – Selina

+0

簡單看看你的代碼,看起來應該使用'async.queue'。在開始工作時開始,限制爲1,一旦你清楚和自信,你可以將限制增加到更高的東西,例如10. –

+0

我會嘗試..謝謝! – Selina

相關問題