Skip to content

Instantly share code, notes, and snippets.

@smailq
Created January 22, 2013 23:54
Show Gist options
  • Save smailq/4600094 to your computer and use it in GitHub Desktop.
Save smailq/4600094 to your computer and use it in GitHub Desktop.
Variables defined in for-loops are accessible from callbacks for `exec` function, however, contents of those variables change as the loop progresses and updates the variable.
# Use Underscore lib to wrap each loop in a func.
exec = require('child_process').exec
_ = require('underscore')._
some_list = [1,2,3]
_.each some_list, (i) ->
exec "ls", (err, stdout, stderr) ->
console.log i
# The result is always
#
# 1
# 2
# 3
exec = require('child_process').exec
some_list = [1,2,3]
for i in some_list
exec "ls", (err, stdout, stderr) ->
console.log i
# The result is NOT always
#
# 1
# 2
# 3
#
# It might even be
#
# 3
# 3
# 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment