You should wrap your code within an IIFE to make your variable persist.
for (var i = 1; i <= 5; i++) {
(function(i) {
lib.request({
path: '/channels/staffpicks/videos',
query: {
page: i,
per_page: 50
}
}, function (error, body, status_code, headers) {
if (error) {
console.log('error');
console.log(error);
} else {
var totalbody = body.total;
console.log('page: ' + i);
}
});
})(i);
}
The "problem" with your current code is that the callback passed to request() isn't fired instantly, therefore when it is called, it gets the "current i" which is 6.
There are 2 easy solutions to have requests' callbacks fired in order.
First solution - call the request after each other.
(function request(i) {
lib.request({
path: '/channels/staffpicks/videos',
query: {
page: i,
per_page: 50
}
}, function (error, body, status_code, headers) {
if (error) {
console.log('error');
console.log(error);
} else {
var totalbody = body.total;
console.log('page: ' + i);
}
request(++i);
});
})(0);
Second - a bit more advanced, but also a better one, because the requests are made at the same time.
var amount = 5,
fetched = 0,
results = new Array(amount);
for (var i = 1; i <= amount; i++) {
(function(i) {
lib.request({
path: '/channels/staffpicks/videos',
query: {
page: i,
per_page: 50
}
}, function (error, body, status_code, headers) {
fetched++;
if (error) {
console.log('error');
console.log(error);
results[i] = "error";
} else {
results[i] = body;
var totalbody = body.total;
}
if (fetched === amount) {
results.forEach(function(body, n) {
console.log('page: ' + n);
});
}
});
})(i);
}
There are better solutions though, but they are a bit more complicated.