无法将值存储在 npm 库 'Sqlite3' 中的 .get 方法中



问题:我使用nodejs库'sqlite3'。

说明:即使我在范围中声明了变量'image_path'image_path似乎正在改变;它不再能够如预期的。

返回。

aim:我只想创建一个函数,我可以使用nodejs查询sqlite3数据库并返回值。如果有更好的方法,那么我目前正在尝试的事情,我将接受它作为答案。

示例:

var sqlite3 = require('sqlite3');
var dataBaseFile = 'test.db';
var dataBase = new sqlite3.Database(dataBaseFile);
function returnImagePath(id){
    var image_path;
    dataBase.serialize(function(){
        var statementReturnImagePath = dataBase.prepare(`SELECT image_path FROM images WHERE id = ${id}`);
        statementReturnImagePath.run();
        statementReturnImagePath.finalize();
        dataBase.get(`SELECT image_path FROM images WHERE id = 1`, function(error, row){
            image_path = row.image_path; 
            console.log(image_path); //image_path is defined here, and logs as expected
        });
        dataBase.close();
    });
    console.log(image_path); //image_path is undefined here
    return image_path;
}
var asdf = returnImagePath(1);
console.log(asdf); //this, therefore doesn't work

在Node.js世界中,您必须了解什么是异步函数。如果一个过程需要IO操作,则不能仅从该过程中返回数据,而必须"等待"数据。我们通常通过回调功能实现此目标。

这是您的示例,

var sqlite3 = require('sqlite3');
var dataBaseFile = 'test.db';
var dataBase = new sqlite3.Database(dataBaseFile);
//callback is a function which accept (err, data)
function returnImagePath(id, callback){
    dataBase.serialize(function(){
        dataBase.get('SELECT image_path FROM images WHERE id = ' + id, function(error, row){
            if (error) {
                //stop and return error if error occurs
                return callback(error, null);
            }
            image_path = row.image_path; 
            console.log(image_path); //image_path is defined here, and logs as expected
            //now you get the image path and return it with callback
            callback(null, image_path);
            dataBase.close();
        });
    });
}
returnImagePath(1, function(err, image_path) {
    if (err) { //capture error(s)
        return console.error(err);
    }
    console.log(image_path); //now you get the image path
});

最新更新