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

169
Visualizações
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 Respostas
Responde à pergunta

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 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