Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callbacks only see last value from loop

Tags:

coffeescript

I have this code:

for food in foods
  Person.eat ->
    console.log food

The problem here is that "food" will always be the last "food" in "foods". That is because I have the console.log in a callback function.

How can I preserve the value in the current iteration?

like image 468
ajsie Avatar asked Dec 27 '22 10:12

ajsie


1 Answers

You need to close over the value of a loop if you want to geneate functions to run later. This what coffee provides the do keyword for.

for food in foods
  do (food) ->
    Person.eat ->
      console.log food

See this example: https://gist.github.com/c8329fdec424de9c57ca

This occurs because your loop body has a reference to the food variable which changes values each time though the loop, and when you function if finds the closure the function was created in and finds that food variable set to the last value of the array. Using another function to in order to create a new scope solves the problem.

like image 142
Alex Wayne Avatar answered Jan 02 '23 03:01

Alex Wayne