Reputation: 3
I have a program in node.js. It connects to a web service that offers a JSON file with data, but the file only shows a limited amount of data (500 records per request), starting with the value of the index parameter in the request. "lastentry" returns the ID of the last record from the current page of data. Lastpage is a boolean that indicates when the last page is reached.
The first request looks like this: http://example.com/data.json?index=0
I build this function to get the ID of the last record. It calls itself until lastpage is true. The index variable increases correctly with every request, according to the value I read from the JSON, but "url" doesn't change and always stays at 0, even though it is built from the index variable. Why is that?
var lastpage = false;
var index = 0;
var url = "http://example.com/data.json?index=" + index;
function getLastEntry() {
request(url, function (err, resp, body) {
if (err || resp.statusCode != 200) {
// error handling
} else {
var data = JSON.parse(body);
index = data.lastentry;
lastpage = data.lastpage;
if (lastpage == false) {
getLastEntry();
}
}
}
}
getLastEntry();
Upvotes: 0
Views: 72
Reputation: 413757
That's not the way JavaScript works. Once you've initialized the variable "url", the initialization expression will never be computed again. You can however arrange for it to happen each time you call "request" by just moving the computation there:
var url = "http://example.com/data.json?index=";
function getLastEntry() {
request(url + index, function (err, resp, body) {
Upvotes: 2