3

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.

toutpt
  • 5,145
  • 5
  • 38
  • 45
  • 1
    This might _seem_ different, but it's really the same as [as the ajax question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/16825593#16825593) - you don't return from an asynchronous query - you pass a callback or use promises instead. – Benjamin Gruenbaum Jan 20 '14 at 20:19

1 Answers1

7

The 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;
            });
        }
}
Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • 2
    Thanks. Now I know I need to think with callback and return results. I'm reading http://callbackhell.com/ – toutpt Jan 20 '14 at 20:51
  • Once you get used to the concept of callbacks the code starts to make more sense and sort of becomes natural. It is true that it can easily turn into callback hell (or the pyramid of doom) just like is true in other languages that people can over-design their OO creations with 17 classes and 6 factories to add two numbers :) – Hector Correa Jan 20 '14 at 20:55
  • So where does the result come out? – imrek Sep 16 '15 at 14:34
  • The results will be in the `rows` parameter. – Hector Correa Sep 16 '15 at 15:39