Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

386
Vistas
Code execution order in for loop when mysql insert nodejs

I have a very simple question that I haven't been able to solve for days. I wrote the following simple code block to give an example.

var mysql = require("mysql")

var connection = mysql.createConnection({
  host: "localhost",
  user: "***",
  password: "***",
  database: "***",
  charset: "utf8mb4"
})

var testArr = ["banana", "apple", "orange", "strawberry"]

for (let fruit of testArr) {
    console.log("fruit check:" + fruit)

    var fruitName = connection.escape(fruit)

    var sql = "INSERT INTO test (name) VALUES (" + fruitName + ")";

    connection.query(sql, function (err, result) {
        if (err) throw err;
        console.log("1 record inserted");
    });
}

The only thing I want to do here is to actually proceed sequentially after entering the for loop. At the moment, the console side comes as follows;

fruit check:banana
fruit check:apple
fruit check:orange
fruit check:strawberry
1 record inserted
1 record inserted
1 record inserted
1 record inserted

I want it to come like this:

fruit check:banana
1 record inserted
fruit check:apple
1 record inserted
fruit check:orange
1 record inserted
fruit check:strawberry
1 record inserted
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try to use promise when you connection your mysql,and use async/await.

you can get approximate answer here

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this approach with async - await and mysql2.
I changed the query to a prepared statement.

const mysql = require('mysql2/promise');

const loadData = async () => {
  try {
    var connection = await mysql.createConnection({
      host: 'localhost',
      user: '***',
      password: '***',
      database: '***',
      charset: 'utf8mb4',
    });

    var testArr = ['banana', 'apple', 'orange', 'strawberry'];

    for (let fruit of testArr) {
      console.log('fruit check:' + fruit);
      var sql = 'INSERT INTO test (name) VALUES (?)';
      await connection.execute(sql, [fruit])
      console.log('1 record inserted');
    }
  } catch (err) {
    throw err; // Or do something else with the error...
  }
};

loadData();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda