如何在函数中返回节点的sqlite3的结果?
问题描述:
我正在尝试在expressjs应用(nodejs)中使用sqlite3
I'm trying to use sqlite3 in an expressjs app (nodejs)
我想创建一个从select语句返回所有结果的函数.
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;
}
}
我知道nodejs是异步的,所以这意味着在查询结束之前调用return.但是我找不到如何使用sqlite的示例.
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.
答
示例中的"return all"行将在this.db.all()调用回调之前执行.为了使代码正常工作,您需要执行以下操作:
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;
});
}
}