0

用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
4

1 回答 1

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
于 2013-10-08T10:28:17.653 回答