I have this:
function afterCreateThePayment(req, res, rows) {
for (var i = 0; i < rows.length; i ) {
console.log(rows.length)
var selecter = "SELECT * from SCHEDULE WHERE CLIENT_USERNAME = ? AND SESSION_STATUS = ?"
//pass rows into this function
mysqlconn.connect(function(err) {
if (err) {
console.error('Database connection failed: ' err.stack);
return;
}
mysqlconn.query(selecter, [rows[i]["USERNAME"], 'CONFIRMED'], async function(err, scheduleData) {
if (err) {
console.log(err);
}
for (var x = 0; x < scheduleData.length; x ) {
console.log(scheduleData[x])
}
// mysqlconn.end();
})
})
}
}
as you can see, i am passing rows into this function, and then trying to use rows[i]["USERNAME"] as one of the query parameters. However, when I do this, I get the error
TypeError: Cannot read property 'USERNAME' of undefined
so i am not sure what to do here, or if my logic is correct. could someone help?
CodePudding user response:
Your issue is that he loop variable i is scoped to afterCreateThePayment. Keep in mind that var in javascript uses functional scoping, which is different than the block scoping you may be familiar with in C-style languages.
I am assuming that the callback from mysqlconn.connect is asynchronous. This means that the loop continues to execute, incrementing i. By the time the callback happens, the loop is out of bounds. If you peek at the value of i (not rows) in your callback you'll see what has happened.
Here is a similar example:
for (var i = 0; i < 5; i )
{
function internal()
{
console.log(i);
}
setTimeout(() => {internal();},1000);
}
The simplest option is swapping out the var i in your loop for let i. Making this change will make the i block scoped, so that the value will apply just to your current call to mysqlconn.connect. In my example, that's simply:
for (let i = 0; i < 5; i )
{
function internal()
{
console.log(i);
}
setTimeout(() => {internal();},1000);
}
