jiy
jiy

Reputation: 868

Nested loops in coffeescript

This isn't working as I expected:

for sup in sups
  getStudents sup.CLKEY, (studs) ->
    console.log "Manager: #{sup.LNAME} Managed By: #{sup.MLNAME}"
    for stud in studs
      console.log "Student #{stud.LNAME} Managed By: #{sup.LNAME}"

getStudents receives each sup.CLKEY, but the rest of the references to sup return value from the last one in the array.

In other words, sup.LNAME and sup.MLNAME in the console.log statements are always from the last sup in the array

How do I nest the 2nd loop so that it stays on the current sup?

Upvotes: 1

Views: 2634

Answers (2)

jiy
jiy

Reputation: 868

Adding "do" made this work:

for sup in sups
  do(sup) ->
    getStudents sup.CLKEY, (studs) ->
      console.log "Manager: #{sup.LNAME} Managed By: #{sup.MLNAME}"
      for stud in studs
        console.log "Student #{stud.LNAME} Managed By: #{sup.LNAME}"

I couldn't get Kim's original solution to work (but it's since been changed to reflect using "do").

Upvotes: 1

Kimtho6
Kimtho6

Reputation: 6184

Ow so you did it like this:

for filename in list
  do (filename) ->
    fs.readFile filename, (err, contents) ->
      compile filename, contents.toString()

Upvotes: 0

Related Questions