JavaScript 同步调用

javascript synchronous call

本文关键字:调用 同步 JavaScript      更新时间:2023-09-26

用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

等待调用所有回调的简单计数器呢?

未经测试的示例:

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