I have below a simple block of JavaScript (stripped down) from a project I'm working on that uses Node.js and Request.
In the third instance where I'm writing to the console, I'm failing to see why the variable xxx
is undefined
. I understand it's a scope issue, but I thought that nested functions like this had access to variables in their parent scope.
I'm certain I'm misunderstanding scope as it pertains to this scenario. Can someone explain to me what is preventing access to this variable, and perhaps a suggestion on how I can otherwise pass this variable into this function to use?
Update - verbatim code below:
In the case below, groups
is defined at the top and is a root-level variable.
(function getListings() {
for (var i = 0; i < groups.length; i++) {
console.log("1: " + JSON.stringify(groups[i]));
var listingReqOptions = { url: format(listingsEndpoint, { "groupID": groups[i][1], "listingID": groups[i][0] }) };
console.log("2: " + JSON.stringify(groups[i]));
request(listingReqOptions, function (error, response, body) {
console.log("3: " + JSON.stringify(groups[i]));
if (!error && response.statusCode == 200) {
var channel = format(listingsChannelTemplate, { "groupID": groups[i][1], "listingID": groups[i][0] });
console.log("adding channel: " + channel);
listingChannels[channel] = JSON.parse(body);
}
else {
console.log("An error occurred while retrieving listing data: " + JSON.stringify(response));
}
});
}
// Loop
setTimeout(getListings, 3000);
})();