0

The var caracnamesecurity works great. But when I put a console.log(caracnamesecurity) inside the response of SELECT AVG. It doestn't work anymore. I don't understand why ..

console.log(results[0]) Console.log(caracnamesecurity) return:

RowDataPacket { 'AVG(rapportqualiteprix)': 2.222222 }
texture f qsf qsd
updated
RowDataPacket { 'AVG(odeur)': 2.088889 }
texture f qsf qsd
updated
RowDataPacket { 'AVG(texture)': 1.022222 }
texture f qsf qsd

But I need this:

RowDataPacket { 'AVG(rapportqualiteprix)': 2.222222 }
rapportqualiteprix f qsf qsd
updated
RowDataPacket { 'AVG(odeur)': 2.088889 }
odeur f qsf qsd
updated
RowDataPacket { 'AVG(texture)': 1.022222 }
texture f qsf qsd

part of code:

  var avisId = results.insertId
  if (typeof scoreAvis !== 'undefined') {
    var i;
    for (i = 0; i < scoreAvis.length; i++) {

      if (scoreAvis[i].score > 0){

        var caracnamesecurity = scoreAvis[i].caracname;
        var scoresecurity = scoreAvis[i].score;

        connection.query("UPDATE avis SET " + caracnamesecurity +"="+ scoresecurity +" WHERE avis.id="+ avisId +"", function (error, results, fields) {
          if (!!error) {
            console.log("error avis");
          } else {
            console.log("updated")
          }
        });


        connection.query("SELECT AVG(" + caracnamesecurity + ") FROM avis WHERE products_id=" + req.body[0].id, function (error, results, fields) {

          console.log(results[0])
          console.log(caracnamesecurity + " f qsf qsd ")
          
        });
     }
}

6
  • its happening because the function connection.query is async Commented Jan 29, 2018 at 12:12
  • @AbhishekAnand hmm.. so What should I do to get the caracname? to put it inside another connection query Commented Jan 29, 2018 at 12:14
  • 1
    one way(not very efficient) is to use the place both connection query in different for loops.The better way is to use promises. Commented Jan 29, 2018 at 12:16
  • hmm okay, I will check how to use promise, thank you Commented Jan 29, 2018 at 12:28
  • you might want to check this too stackoverflow.com/questions/37830001/… Commented Jan 29, 2018 at 12:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.