Before going into the query, the issues object is defined, inside of the issues query it is undefined. I tried a solution mentioned on posts of the same type, but it did not work. Comments in the code explain the issue further.
var createIssues = function createIssues(rows, wrap) {
var issues = [];
for (var i = 0; i < rows.length; i++) {
// Processing code redacted
issues.push({
id : rows[i].id,
// Other field redacted
});
// ISSUES OBJECT CORRECT HERE
console.log(JSON.stringify(issues[i]))
// Query comments for individual post
connection.query(
"SELECT C.id, C.elementID, C.googleID, C.time, C.body FROM comments C WHERE elementID = ? AND approved = 1", issues[i].id,
function (err, rows_comments) {
// ISSUES OBJECT UNDEFINED HERE
console.log(JSON.stringify(issues[i]))
// More code redacted
}
)
}
return issues;
}
I tried passing it in as a function, similar to how I found in explanations online, but now it is saying "TypeError: undefined is not a function"
var createIssues = function createIssues(rows, wrap) {
var issues = []; // Create issues array
// Loop throug every issue that was
// returned by the SQL query.
for (var i = 0; i < rows.length; i++) {
// Redacted processing code
issues.push({
id : rows[i].id,
// Redacted extra fields
});
(function(issues) {
connection.query(
"SELECT C.id, C.elementID, C.googleID, C.time, C.body FROM comments C WHERE elementID = ? AND approved = 1", issues[i].id,
function (err, rows_comments) {
// Can't access issues here, undefined
}
)
})(issues);
}
return issues;
}
i > rows.lengthby the time the query completesi == rows.lengthactuallylet iinstead ofvar iin your for loop, it would work. but that requires using either node.js 4 or the --harmony flag. using Array.prototype.forEach instead of a for loop to loop over an array would also solve it. Good programming practices are good practices because they avoid problems. If you can usetheArray.forEach, do it.