2

i'm trying to use sqlite3 in node.js script, i'm using this library:

https://github.com/mapbox/node-sqlite3

but i want that the call at the database is synchronous and not asynchronous, this is an example of the code i use:

var tests = [];

db.serialize(function() {

  db.each("SELECT lot_id, status FROM TestTable ORDER BY lot_id ASC", function(err, row) {
      tests.push(row.status);
      console.log("Read "+row.lot_id+" state: "+row.status);
  });
});

db.close();

for (i = 0; i < tests.length; i++) {
//Do something
}

when the execution arrives at the for loop, go over because the tests array is still empty, how i can perform this instruction sequentially?

thanks

1 Answer 1

4

Execute the for-loop in the complete callback

var tests = [];

db.serialize(function() {

  db.each("SELECT lot_id, status FROM TestTable ORDER BY lot_id ASC", function(err, row) {
      tests.push(row.status);
      console.log("Read "+row.lot_id+" state: "+row.status);
  }, function() { // this callback is executed when the query completed
     for (i = 0; i < tests.length; i++) {
     // Do something
     }
  });
});

db.close();
Sign up to request clarification or add additional context in comments.

3 Comments

i have a very lot of code to execute after the for-loop, i can insert all this code in the serialize? there isn't a better solution?
You can put this code in a function and call that function from the complete callback.
Worked for me !!! I could not find any documentation from the npm sqlite3 wiki and this helped me!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.