How to return results of node's sqlite3 in a function?

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.

Answers:

Answer

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;
            });
        }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.