Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I see I'm late, but anyway:</p> <p>When putting a function in a loop, or recursion, variables in closures are evaluated at the time the function is executed, not when it is created. So</p> <pre><code>for (i in [1, 2, 3]) { setTimeout(function() { console.log(i); }, 1000); } </code></pre> <p>returns</p> <pre><code>3 3 3 </code></pre> <p>but</p> <pre><code>for (i in [1, 2, 3]) { setTimeout(function(i) { return function() { console.log(i); }; }(i), 1000); } </code></pre> <p>will correctly give you</p> <pre><code>1 2 3 </code></pre> <p>This is why it is generally not recommended to put function definitions in a loop.</p> <p>Anyway, here is corrected code for you, note it console.logs everything in correct order:</p> <pre><code>var http = require('http'); var querystring = require('querystring'); var myArr = [1,2,3,4,5,6,7,8,9,10,11,12]; function requestSender(d, callback) { var post = querystring.stringify({ data: d }); var options = { hostname: 'www.example.com', port: 80, path: '/upload', method: 'POST' }; var req = http.request(options, function(res) { res.setEncoding('utf-8'); res.on('data', function(data) { console.log(d); console.log(data); callback(); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(post); req.end(); } function stack(arr) { var newArr = arr.slice(1); arr[0](function(arg) { return function() { if (arg.length &gt; 0) stack(arg); }; }(newArr)); } var functionsArr = []; for (i in myArr) { functionsArr.push(function(i) { return function(callback) { var value = myArr[i]; requestSender(value, callback); }; }(i)); } stack(functionsArr); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload