title: Calling an asynchronous function within a for loop in JavaScript
body: <p>I have the following code:</p>
  
  <pre><code>for(var i = 0; i &lt; list.length; i++){
      mc_cli.get(list[i], function(err, response) {
          do_something(i);
      });
  }
  </code></pre>
  
  <p><code>mc_cli</code> is a connection to a memcached database. As you can imagine, the callback function is asynchronous, thus it may be executed when the for loop already ended. Also, when calling in this way <code>do_something(i)</code> it always uses the last value of the for loop.</p>
  
  <p>I tried with a closure in this way </p>
  
  <pre><code>do_something((function(x){return x})(i)) 
  </code></pre>
  
  <p>but apparently this is again using always the last value of the index of the for loop. </p>
  
  <p>I also tried declaring a function before the for loop like so:</p>
  
  <pre><code>var create_closure = function(i) {
      return function() {
          return i;
      }
  }
  </code></pre>
  
  <p>and then calling </p>
  
  <pre><code>do_something(create_closure(i)())
  </code></pre>
  
  <p>but again without success, with the return value always being the last value of the for loop.</p>
  
  <p>Can anybody tell me what am I doing wrong with closures? I thought I understood them but I can't figure why this is not working.</p>