I'm trying to use sqlite3 in an expressjs app (nodejs)
I want to create a function that returns all the results from a select statement. This function will be called by a route that
var queryGetAll = 'SELECT id, title, description, modified, lat, lng, zoom FROM maps';
function Manager(){
this.db = null;
this.getAll = function(){
var all = [];
this.db.all(queryGetAll, function(err, rows){
if (err){
throw err;
}
all.push.apply(all, rows);
});
return all;
}
}
I know nodejs is asynch, so it means the return is called before the end of the query. But I don't find examples on how I should use sqlite.
I'm trying to use sqlite3 in an expressjs app (nodejs)
I want to create a function that returns all the results from a select statement. This function will be called by a route that
var queryGetAll = 'SELECT id, title, description, modified, lat, lng, zoom FROM maps';
function Manager(){
this.db = null;
this.getAll = function(){
var all = [];
this.db.all(queryGetAll, function(err, rows){
if (err){
throw err;
}
all.push.apply(all, rows);
});
return all;
}
}
I know nodejs is asynch, so it means the return is called before the end of the query. But I don't find examples on how I should use sqlite.
Share Improve this question asked Jan 20, 2014 at 20:17 toutpttoutpt 5,2206 gold badges41 silver badges45 bronze badges 1- 1 This might seem different, but it's really the same as as the ajax question - you don't return from an asynchronous query - you pass a callback or use promises instead. – Benjamin Gruenbaum Commented Jan 20, 2014 at 20:19
1 Answer
Reset to default 7The line "return all" in your example will be executed BEFORE this.db.all() calls your callback. In order for your code to work you need to do something like this:
var queryGetAll = 'SELECT id, title, description, modified, lat, lng, zoom FROM maps';
function Manager(){
this.db = null;
// Allow a callback function to be passed to getAll
this.getAll = function(callback){
this.db.all(queryGetAll, function(err, rows){
if (err){
// call your callback with the error
callback(err);
return;
}
// call your callback with the data
callback(null, rows);
return;
});
}
}