jiy
jiy

Reputation: 868

coffeescript looping through array and adding values

What I'd like to do is add an array of students to each manager (in an array).

This is where I'm getting stuck:

      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

EDIT: After some thought, what may be happening is that it is adding the "sudents_b" data to the sups array, but the sups array is being returned (via cback function) before this work is performed. Thus, I suppose I should move that work to a function and only return sups after another callback is performed?

For context, here's the gist of this code:

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

Upvotes: 0

Views: 433

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39223

You are correct that your callback cback subs is executed before even the first getStudents has executed it's callback with the studs array. Since you want to do this for a whole array, it can grow a little hairy with just a for loop.

I always recommend async for these things:

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.

Edit: Or if you want to put students on each sup, you would have this 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

Edit: Also, you should probably follow the node custom of passing err as the first argument to all callbacks, and do proper error checking.

Upvotes: 1

Related Questions