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.
As I do not know how many times I have to do the request, I am using async.whilst(). 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).
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 + '&offset=' + i*20;
request(
reqURL,
function (err, resp, body) {
if(!err && 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();
}
The test output is like this:
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&offset=80
Request #5 done
http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80
Request #5 done
http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80
Request #5 done
http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80
Request #5 done
http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80
Request #5 done
the request method is somehow only taking into account the final i value of 80. What did I do wrong, and how do I fix this?