Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to execute http requests strictly one by one in node.js?
    primarykey
    data
    text
    <p>So, I have an array of some values. I'd like to send these values to www.example.com. I have to send only one value per request.</p> <p>I am using for this task http.request in node.js:</p> <pre><code>var myArr = [1,2,3,4,5,6,7,8,9,10,11,12]; function requestSender(data, callback) { var post = querystring.stringify({ data: data }); var options = { hostname: 'www.example.com', port: 80, path: '/upload', method: 'POST' }; var req = https.request(options, function(res) { res.setEncoding('utf-8'); res.on('data', function(data) { callback(); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(post); req.end(); } </code></pre> <p>To send requests one by one I am using function, that takes an array of functions and recursively adds next function as the callback to previous:</p> <pre><code>function stack(arr) { var newArr = arr.slice(1); arr[0](function() { if (typeof newArr[0] == 'function') stack(newArr); }); } </code></pre> <p>And to compile all this staff into one, I am using the following code:</p> <pre><code>var functionsArr = []; for (i in myArr) { functionsArr.push(function(callback) { var value = myArr[i]; requestSender(value, callback); }); }; stack(functionsArr); </code></pre> <p>But actually, this does not work: all requests are sent in 1 millisecond, and after that callbacks are listening while responses are recieved. But it should not! I have put <em>callback()</em> in http.request(options, <strong>callback</strong>)!! How does it happen?</p> <p>So my questions are: 1) How can I send http requests strictly one by one in node.js? 2) Why does not my solution work?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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