Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!