The problem is occurring because your reqURL
variable has no var
, and does not belong to the doThisEveryTime
scope. You are also making all your requests at once, since you are not waiting for a request to complete before calling next
. These two things are leading the request to happen five times at the same time with the same URL. Try the following:
function doThisEveryTime(next) {
var 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 += 1;
if (i === 5) {
continueWhilst = false;
}
console.log("Iterating, i= " + i);
// This is in the callback for request now.
next();
});
}