【问题标题】:coffeescript looping through array and adding values咖啡脚本循环遍历数组并添加值
【发布时间】:2012-04-10 05:40:19
【问题描述】:

我想做的是向每个经理添加一组学生(在一个数组中)。

这是我卡住的地方:

      for sup in sups
        do(sup) ->
          sup.students_a = "This one works"
          getStudents sup.CLKEY, (studs) ->
            sup.students_b = "This one doesn't"
      cback sups

编辑:经过一番思考,可能发生的情况是它正在将“sudents_b”数据添加到 sups 数组,但在执行这项工作之前(通过 cback 函数)返回了 sups 数组。因此,我想我应该将这项工作转移到一个函数中,并且只在执行另一个回调之后才返回 sups?

关于上下文,这里是这段代码的要点:

odbc = require "odbc"

module.exports.run = (managerId, cback) ->
  db2 = new odbc.Database()
  conn = "dsn=mydsn;uid=myuid;pwd=mypwd;database=mydb"
  db2.open conn, (err) ->
    throw err if err

    sortBy = (key, a, b, r) ->
      r = if r then 1 else -1
      return -1*r if a[key] > b[key]
      return +1*r if b[key] > a[key]
      return 0

    getDB2Rows = (sql, params, cb) ->
      db2.query sql, params, (err, rows, def) ->
        if err? then console.log err else cb rows

    getManagers = (mid, callback) ->
      supers = []
      queue = []

      querySupers = (id, cb) ->
        sql = "select distinct mycolumns where users.id = ? and users.issupervisor = 1"
        getDB2Rows sql, [id], (rows) ->
          for row in rows
            do(row) ->
              if supers.indexOf row is -1 then supers.push row
              if queue.indexOf row is -1 then queue.push row
          cb null

      addSupers = (id) -> # todo: add limit to protect against infinate loop
        querySupers id, (done) ->
          shiftrow = queue.shift()
          if shiftrow? and shiftrow['CLKEY']? then addSupers shiftrow['CLKEY'] else
            callback supers

      addMain = (id) ->
        sql = "select mycolumns where users.id = ? and users.issupervisor = 1"
        getDB2Rows sql, [id], (rows) ->
          supers.push row for row in rows

      addMain mid
      addSupers mid

    getStudents = (sid, callb) ->
      students = []

      sql = "select mycols from mytables where myconditions and users.supervisor = ?"
      getDB2Rows sql, [sid], (datas) ->
        students.push data for data in datas
        callb students

    console.log "Compiling Array of all Managers tied to ID #{managerId}..."
    getManagers managerId, (sups) ->
      console.log "Built array of #{sups.length} managers"
      sups.sort (a,b) ->
        sortBy('MLNAME', a, b) or # manager's manager
        sortBy('LNAME', a, b) # manager
      for sup in sups
        do(sup) ->
          sup.students_a = "This one works"
          getStudents sup.CLKEY, (studs) ->
            sup.students_b = "This one doesn't"
      cback sups

【问题讨论】:

    标签: arrays loops coffeescript iteration


    【解决方案1】:

    您的回调 cback subs 在第一个 getStudents 使用 studs 数组执行回调之前执行是正确的。由于您想对整个数组执行此操作,因此仅使用 for 循环可能会变得有点麻烦。

    对于这些事情,我总是推荐async

    getter = (sup, callback) ->
      getStudents sup.CLKEY, callback
    
    async.map sups, getter, (err, results) ->
      // results is an array of results for each sup
      callback() // <-- this is where you do your final callback.
    

    编辑: 或者,如果你想在每个 sup 上加上 students,你会得到这个 getter

    getter = (sup, callback) ->
      getStudents sup.CLKEY, (studs) ->
        sup.students = studs
        // async expects err as the first parameter to callbacks, as is customary in node
        callback null, sup
    

    编辑:另外,您可能应该遵循将err 作为第一个参数传递给所有回调的节点习惯,并进行适当的错误检查。

    【讨论】:

    • 非常感谢 - 效果很好!还在我所有的回调中添加“err”。
    • 太棒了!我建议您通读 async 简短但出色的文档,其中有很多用于使用回调执行 mapforEachfilter 等的好东西,以及像 parallelqueue 等控制流。
    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    相关资源
    最近更新 更多