I'm trying to read all records in a sqlite3 table and return them via callback. But it seems that despite using serialize these calls are still ASYNC. Here is my code:
var readRecordsFromMediaTable = function(callback){
var db = new sqlite3.Database(file, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
var allRecords = [];
db.serialize(function() {
db.each("SELECT * FROM MediaTable", function(err, row) {
myLib.generateLog(levelDebug, util.inspect(row));
allRecords.push(row);
}
callback(allRecords);
db.close();
});
}
When the callback gets fired the array prints '[]'.
Is there another call that I can make (instead of db.each) that will give me all rows in one shot. I have no need for iterating through each row here.
If there isn't, how do I read all records and only then call the callback with results?
I know I'm kinda late, but since you're here, please consider this:
As described in the
node-sqlite3
docs, you should use.each()
if you're after a very large or unknown number or rows, since.all()
will store all result set in memory before dumping it.That being said, take a look at Colin Keenan's answer.
The accepted answer using db.all with a callback is correct since db.each wasn't actually needed. However, if db.each was needed, the solution is provided in the node-sqlite3 API documentation, https://github.com/mapbox/node-sqlite3/wiki/API#databaseeachsql-param--callback-complete:
So, where you end the first callback, instead of just } put }, function() {...}. Something like this:
I was able to find answer to this question. Here it is for anyone who is looking:
A promise based method
I tackled this differently, since these calls are asynchronous you need to wait until they complete to return their data. I did it with a
setInterval()
, kind of like throwing pizza dough up into the air and waiting for it to come back down.