2013-10-07 58 views
0

用coffeescript編寫,但原理相同,我調用ps.list和ps.read(從npm註冊表中的pslook模塊)。這些函數不返回結果,而是調用傳遞給它們的回調函數。 setTimeout不是我想要做的,但是在想辦法解決這個問題時遇到麻煩..有什麼想法?不確定IcedCoffeeScript可以以任何方式幫助您?javascript同步調用

ps = require 'pslook' 

instances = [] 

ps.list (err, results) -> 
    if err then throw err 
    results.forEach (result) -> 
    ps.read result.pid, (err, process) -> 
     if err then throw err 
     instances.push process.cmdline 
    , 'fields': ps.ALL 
, 'search': /^ssh/ 

setTimeout -> 
    console.dir instances 
    ### Do lots more stuff here with the list of instances that I don't want to be nested within calls to ps.list/ps.read 
, 500 
+1

你所面對的是等到所有異步任務完成作業經典問題。看看這個:http://stackoverflow.com/questions/10551499/simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript有很多很好的解決方案。 – freakish

回答

1

怎麼樣一個簡單的計數器,等待所有的回調被調用?

未經測試的例子:

ps.list (err, results) -> 
    if err then throw err 
    waitingFor = results.length 
    results.forEach (result) -> 
    ps.read result.pid, (err, process) -> 
     if err then throw err 
     instances.push process.cmdline 
     waitingFor -= 1 
     goOn(instances) if waitingFor == 0 
    , 'fields': ps.ALL 
, 'search': /^ssh/ 

goOn (instances) -> 
    console.dir instances 
+0

還沒有測試過,但邏輯似乎明智。謝謝 – gratz