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

168
Vistas
Incorrect sorrting by insert with forEach

I have an array with objects. I want to import these into a sqlite3 database. I do this with a forEach loop. It works well. But I wonder why the objects are not imported in the order I put them into the database.

This is what I do

const comments = [
  {post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
  {post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
]

comments.forEach(c => {
    sql = `INSERT INTO comments(post_id, comment, comment_author) VALUES (?,?,?)`
    db.run(sql, [c.post_id, c.comment, c.comment_author], (err) => {
        if (err) { console.log(err.message)};
    });
});

If I now execute a select, I get the following pure order (take a look to post_id):

[
  {id: 1, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
  {id: 2, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"}
]

Question Why is this happening? And what can I do to change the behavior.

Expected result:

[
  {id: 1, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
  {id: 2, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"}
]

Note I Guess it has something to do with the async of javascript.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are right with your guess: I Guess it has something to do with the async of javascript.!

let placeholders = comments.map((c) => '(?)').join(',');
let sql = 'INSERT INTO comments(post_id, comment, comment_author) VALUES ' + placeholders;

// output the INSERT statement
console.log(sql);

db.run(sql, [comments], (err, results, fields) => {
  if (err) {
    return console.error(err.message);
  }
  // get inserted rows
  console.log('Row inserted:' + results.affectedRows);
});

// close the database connection
db.close();
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