Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

Problem courtesy of: toutpt

Solution

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;
            });
        }
}
Solution courtesy of: Hector Correa

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×