javascript同步调用

时间:2013-10-07 12:04:43

标签: javascript coffeescript

用coffeescript写,但原理是一样的,我正在调用ps.list和ps.read(来自npm注册表中的pslook模块)。这些函数不返回结果,而是调用传递给它们的回调。 setTimeout不是我想要做的,但我很难想到解决这个问题的方法......任何想法?不确定IcedCoffeeScript能否以任何方式提供帮助?

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 个答案:

答案 0 :(得分: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