The problem isn't specific to coffee-script. It's that javascript doesn't have block scope, so you can't create a FOR loop the way you're doing it. Here's an SO post on it, with an explanation and the solution:
http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example On Monday, July 23, 2012 2:33:16 PM UTC-4, Jose wrote: > > Hi all, > I have asked this question of the issues page of the coffee-script account > on github. However, I believe it is also relevant to the node.js community. > > I am trying to understand callbacks within for loops. Suppose I have two > methods mth1 and mth2 as follows: > > > mth1: (item, callback) -> > callback null, item > > mth2: (my_array, cb) -> > for my_item in my_array > @mth1 my_item, (error, result) => > if error? > cb error, null > cb null, "done" > > I have noticed that this code binds the last my_item to all the function > (mth1) calls. Is that the normal behavior? Is there something I forgot to > do? > I also have a couple more questions regarding callbacks within loops. > Consider the following code: > > > class CB_test > constructor: > # constructor code goes here > > # Just an ordinary method > another_method: (item, cb) -> > cb null, item > > outer_method: (my_array, callback) -> > @inner_method my_item, callback for my_item in my_array > callback null, "Outer method completed" > > inner_method:(my_item, cb1) -> > @another_method my_item, (error, result) => > if error? > cb1 error, null > > Obviously, what I wanna do here is similar to the previous case, but with > a correct binding. However, if an error occurs in*inner_method*, cb1 > error, null will be called first, and then callback null, Outer method > completed will be called. How do I circumvent that? Any thought? > Thanks in advance > José > -- Job Board: http://jobs.nodejs.org/ Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines You received this message because you are subscribed to the Google Groups "nodejs" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nodejs?hl=en?hl=en
