0

Writing in coffeescript but the principle is the same, I'm calling ps.list and ps.read (from the pslook module in the npm registry). These functions don't return results but call the callback passed to them. The setTimeout is not what I want to do, but am having trouble thinking of a way around this.. any ideas? Not sure if IcedCoffeeScript can help here in any way?

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
gratz
  • 1,506
  • 3
  • 16
  • 34
  • 1
    You are dealing with classical problem of waiting until all asynchronous tasks finish the job. Check this out: http://stackoverflow.com/questions/10551499/simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript There are many good solutions there. – freakish Oct 07 '13 at 12:17

1 Answers1

1

What about a simple counter that waits for all callbacks to be called?

Untested example:

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
Sebastian vom Meer
  • 5,005
  • 2
  • 28
  • 36