Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
passing data to function and using it node.js sql

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda