title: How to asynchronously do multiple REST API requests in node.js?
body: <p>What I want to do is do multiple remote REST API requests, where I want each request to be done sequentially, one after another. I read that async.js is the way to do this.</p>
  
  <p>As I do not know how many times I have to do the request, I am using <code>async.whilst()</code>. The idea is that I will stop requesting once the API returns zero posts. Here is my code so far (for testing purposes I limited the loop to run for 5 times only).</p>
  
  <pre><code>var request = require('request');
  var async   = require('async');
  
  var APIKEY  = 'api-key-here';
  
  var i = 0;
  var continueWhilst = true;
  async.whilst(
    function test() { return continueWhilst; },
    doThisEveryTime,
    function (err) {
      // Done
    }
  );
  
  function doThisEveryTime(next) {
  
    reqURL = 'http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=' + APIKEY + '&amp;offset=' + i*20;  
  
    request(
      reqURL,
      function (err, resp, body) {
        if(!err &amp;&amp; resp.statusCode == 200) {
          var resultAsJSON = JSON.parse(body);      
          console.log(reqURL);        
          console.log("Request #" + i + " done");
      }
    });
  
    i++;
    if (i===5) {
      continueWhilst = false;
    }
    console.log("Iterating, i= " + i);
    next();
  }
  </code></pre>
  
  <p>The test output is like this:</p>
  
  <pre><code>Iterating, i= 1
  Iterating, i= 2
  Iterating, i= 3
  Iterating, i= 4
  Iterating, i= 5
  http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&amp;offset=80
  Request #5 done
  http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&amp;offset=80
  Request #5 done
  http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&amp;offset=80
  Request #5 done
  http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&amp;offset=80
  Request #5 done
  http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&amp;offset=80
  Request #5 done
  </code></pre>
  
  <p>the <code>request</code> method is somehow only taking into account the final <code>i</code> value of 80. What did I do wrong, and how do I fix this?</p>