javascript for loop only return the last element

Why the loop only return the last value?

Can someone help me to get all the values return in the SQL insert

tableau.forEach(function(obj) {

    for(let i = 0; i < obj.produits.length; i++) {
        let bd_nom = obj.produits[ii].nom
        let bd_description = obj.produits[ii].description
        let bd_titre = obj.titre

        records = [[bd_nom, bd_description, bd_titre]]

        con.connect(function(err) {
            let sql = "INSERT INTO scrapeded (nom, text, titre) VALUES ?";
            con.query(sql, [records], function (err, result) {
                console.log(result)
                console.log("Nombre de rangée affectée : " + result.affectedRows)
                console.log("Nombre d'enregistrement affectée avec avertissement : " + result.warningCount)
                console.log("Message du serveur mySQL : " + result.message)
            })
         })
      }
  })

Upvotes: 0

Views: 59

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

You're implicitly assigning and reassigning to the global variable records on each iteration. So, by the time the asynchronous query starts, the main thread has ended and records remains as the last value it was assigned.

Declare it with const instead to ensure that there's a new binding for each iteration.

Also, there's no need to declare an array and then immediately destructure it to select the first element - instead, simply declare records as a single-dimensional array with two items:

tableau.forEach(function(obj) {
  for(let i = 0; i < obj.produits.length; i++) {
    let bd_nom = obj.produits[ii].nom
    let bd_description = obj.produits[ii].description
    let bd_titre = obj.titre

    const records = [bd_nom, bd_description, bd_titre]

    con.connect(function(err) {
      let sql = "INSERT INTO scrapeded (nom, text, titre) VALUES ?";
      con.query(sql, records, function (err, result) {
        console.log(result)
        console.log("Nombre de rangée affectée : " + result.affectedRows)
        console.log("Nombre d'enregistrement affectée avec avertissement : " + result.warningCount)
        console.log("Message du serveur mySQL : " + result.message)
      })
    })
  }
})

Upvotes: 2

Related Questions