最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return results of node's sqlite3 in a function? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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;
            });
        }
}
发布评论

评论列表(0)

  1. 暂无评论