title: Javascript & promises with Q - closure problems in promises
body: <p>I'm using Node.js and Q to write server-side asynchronous code. I'm new to promises (and I'm new to asynchronous programming in general), and I'm having a bit of trouble that I haven't been able to solve by staring at the Q documentation. Here's my code (it's coffeescript - let me know if you want to see the javascript instead):</p>
  
  <pre><code>templates = {}
  promises = []
  for type in ['html', 'text']
      promises.push Q.nfcall(fs.readFile
          , "./email_templates/#{type}.ejs"
          , 'utf8'
          ).then (data)-&gt;
              # the problem is right here - by the time
              # this function is called, we are done
              # iterating through the loop, and the value 
              # of type is incorrect
              templates[type] = data
  Q.all(promises).then(()-&gt;
      console.log 'sending email...'
      # send an e-mail here...
  ).done ()-&gt;
      # etc
  </code></pre>
  
  <p>Hopefully my comments explained the problem. I want to iterate through a list of types, and then run a chain of promises for each type, but the problem is that the value of <code>type</code> is being changed outside of the scope of the promises. I realize that, for such a short list, I can just unroll the loop, but this is not a sustainable solution. How can I ensure that each promise sees a different yet locally correct value of <code>type</code>?</p>